[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wpdb.php (summary)

WordPress database access abstraction class. Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}

File Size: 4134 lines (118 kb)
Included or required: 2 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

wpdb:: (72 methods):
  __construct()
  __get()
  __set()
  __isset()
  __unset()
  init_charset()
  determine_charset()
  set_charset()
  set_sql_mode()
  set_prefix()
  set_blog_id()
  get_blog_prefix()
  tables()
  select()
  _weak_escape()
  _real_escape()
  _escape()
  escape()
  escape_by_ref()
  quote_identifier()
  _escape_identifier_value()
  prepare()
  esc_like()
  print_error()
  show_errors()
  hide_errors()
  suppress_errors()
  flush()
  db_connect()
  parse_db_host()
  check_connection()
  query()
  _do_query()
  log_query()
  placeholder_escape()
  add_placeholder_escape()
  remove_placeholder_escape()
  insert()
  replace()
  _insert_replace_helper()
  update()
  delete()
  process_fields()
  process_field_formats()
  process_field_charsets()
  process_field_lengths()
  get_var()
  get_row()
  get_col()
  get_results()
  get_table_charset()
  get_col_charset()
  get_col_length()
  check_ascii()
  check_safe_collation()
  strip_invalid_text()
  strip_invalid_text_from_query()
  strip_invalid_text_for_column()
  get_table_from_query()
  load_col_info()
  get_col_info()
  timer_start()
  timer_stop()
  bail()
  close()
  check_database_version()
  supports_collation()
  get_charset_collate()
  has_cap()
  get_caller()
  db_version()
  db_server_info()


Class: wpdb  - X-Ref

WordPress database access abstraction class.

This class is used to interact with a database without needing to use raw SQL statements.
By default, WordPress uses this class to instantiate the global $wpdb object, providing
access to the WordPress database.

It is possible to replace this class with your own by setting the $wpdb global variable
in wp-content/db.php file to your class. The wpdb class will still be included, so you can
extend it or simply use your own.

__construct( $dbuser, $dbpassword, $dbname, $dbhost )   X-Ref
Connects to the database server and selects a database.

Does the actual setting up
of the class properties and connection to the database.

param: string $dbuser     Database user.
param: string $dbpassword Database password.
param: string $dbname     Database name.
param: string $dbhost     Database host.

__get( $name )   X-Ref
Makes private properties readable for backward compatibility.

param: string $name The private member to get, and optionally process.
return: mixed The private member.

__set( $name, $value )   X-Ref
Makes private properties settable for backward compatibility.

param: string $name  The private member to set.
param: mixed  $value The value to set.

__isset( $name )   X-Ref
Makes private properties check-able for backward compatibility.

param: string $name The private member to check.
return: bool If the member is set or not.

__unset( $name )   X-Ref
Makes private properties un-settable for backward compatibility.

param: string $name  The private member to unset

init_charset()   X-Ref
Sets $this->charset and $this->collate.


determine_charset( $charset, $collate )   X-Ref
Determines the best charset and collation to use given a charset and collation.

For example, when able, utf8mb4 should be used instead of utf8.

param: string $charset The character set to check.
param: string $collate The collation to check.
return: array {

set_charset( $dbh, $charset = null, $collate = null )   X-Ref
Sets the connection's character set.

param: mysqli $dbh     The connection returned by `mysqli_connect()`.
param: string $charset Optional. The character set. Default null.
param: string $collate Optional. The collation. Default null.

set_sql_mode( $modes = array()   X-Ref
Changes the current SQL mode, and ensures its WordPress compatibility.

If no modes are passed, it will ensure the current MySQL server modes are compatible.

param: array $modes Optional. A list of SQL modes to set. Default empty array.

set_prefix( $prefix, $set_table_names = true )   X-Ref
Sets the table prefix for the WordPress tables.

param: string $prefix          Alphanumeric name for the new prefix.
param: bool   $set_table_names Optional. Whether the table names, e.g. wpdb::$posts,
return: string|WP_Error Old prefix or WP_Error on error.

set_blog_id( $blog_id, $network_id = 0 )   X-Ref
Sets blog ID.

param: int $blog_id
param: int $network_id Optional. Network ID. Default 0.
return: int Previous blog ID.

get_blog_prefix( $blog_id = null )   X-Ref
Gets blog prefix.

param: int $blog_id Optional. Blog ID to retrieve the table prefix for.
return: string Blog prefix.

tables( $scope = 'all', $prefix = true, $blog_id = 0 )   X-Ref
Returns an array of WordPress tables.

Also allows for the `CUSTOM_USER_TABLE` and `CUSTOM_USER_META_TABLE` to override the WordPress users
and usermeta tables that would otherwise be determined by the prefix.

The `$scope` argument can take one of the following:

- 'all' - returns 'all' and 'global' tables. No old tables are returned.
- 'blog' - returns the blog-level tables for the queried blog.
- 'global' - returns the global tables for the installation, returning multisite tables only on multisite.
- 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
- 'old' - returns tables which are deprecated.

param: string $scope   Optional. Possible values include 'all', 'global', 'ms_global', 'blog',
param: bool   $prefix  Optional. Whether to include table prefixes. If blog prefix is requested,
param: int    $blog_id Optional. The blog_id to prefix. Used only when prefix is requested.
return: string[] Table names. When a prefix is requested, the key is the unprefixed table name.

select( $db, $dbh = null )   X-Ref
Selects a database using the current or provided database connection.

The database name will be changed based on the current database connection.
On failure, the execution will bail and display a DB error.

param: string $db  Database name.
param: mysqli $dbh Optional. Database connection.

_weak_escape( $data )   X-Ref
Do not use, deprecated.

Use esc_sql() or wpdb::prepare() instead.

param: string $data
return: string

_real_escape( $data )   X-Ref
Real escape using mysqli_real_escape_string().

param: string $data String to escape.
return: string Escaped string.

_escape( $data )   X-Ref
Escapes data. Works on arrays.

param: string|array $data Data to escape.
return: string|array Escaped data, in the same type as supplied.

escape( $data )   X-Ref
Do not use, deprecated.

Use esc_sql() or wpdb::prepare() instead.

param: string|array $data Data to escape.
return: string|array Escaped data, in the same type as supplied.

escape_by_ref( &$data )   X-Ref
Escapes content by reference for insertion into the database, for security.

param: string $data String to escape.

quote_identifier( $identifier )   X-Ref
Quotes an identifier for a MySQL database, e.g. table/field names.

param: string $identifier Identifier to escape.
return: string Escaped identifier.

_escape_identifier_value( $identifier )   X-Ref
Escapes an identifier value without adding the surrounding quotes.

- Permitted characters in quoted identifiers include the full Unicode
Basic Multilingual Plane (BMP), except U+0000.
- To quote the identifier itself, you need to double the character, e.g. `a``b`.

param: string $identifier Identifier to escape.
return: string Escaped identifier.

prepare( $query, ...$args )   X-Ref
Prepares a SQL query for safe execution.

Uses `sprintf()`-like syntax. The following placeholders can be used in the query string:

- `%d` (integer)
- `%f` (float)
- `%s` (string)
- `%i` (identifier, e.g. table/field names)

All placeholders MUST be left unquoted in the query string. A corresponding argument
MUST be passed for each placeholder.

Note: There is one exception to the above: for compatibility with old behavior,
numbered or formatted string placeholders (eg, `%1$s`, `%5s`) will not have quotes
added by this function, so should be passed with appropriate quotes around them.

Literal percentage signs (`%`) in the query string must be written as `%%`. Percentage wildcards
(for example, to use in LIKE syntax) must be passed via a substitution argument containing
the complete LIKE string, these cannot be inserted directly in the query string.
Also see wpdb::esc_like().

Arguments may be passed as individual arguments to the method, or as a single array
containing all arguments. A combination of the two is not supported.

Examples:

$wpdb->prepare(
"SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
array( 'foo', 1337, '%bar' )
);

$wpdb->prepare(
"SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s",
'foo'
);

param: string      $query   Query statement with `sprintf()`-like placeholders.
param: array|mixed $args    The array of variables to substitute into the query's placeholders
param: mixed       ...$args Further variables to substitute into the query's placeholders
return: string|void Sanitized query string, if there is a query to prepare.

esc_like( $text )   X-Ref
First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL.

Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.

Example Prepared Statement:

$wild = '%';
$find = 'only 43% of planets';
$like = $wild . $wpdb->esc_like( $find ) . $wild;
$sql  = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );

Example Escape Chain:

$sql  = esc_sql( $wpdb->esc_like( $input ) );

param: string $text The raw text to be escaped. The input typed by the user
return: string Text in the form of a LIKE phrase. The output is not SQL safe.

print_error( $str = '' )   X-Ref
Prints SQL/DB error.

param: string $str The error to display.
return: void|false Void if the showing of errors is enabled, false if disabled.

show_errors( $show = true )   X-Ref
Enables showing of database errors.

This function should be used only to enable showing of errors.
wpdb::hide_errors() should be used instead for hiding errors.

param: bool $show Optional. Whether to show errors. Default true.
return: bool Whether showing of errors was previously active.

hide_errors()   X-Ref
Disables showing of database errors.

By default database errors are not shown.

return: bool Whether showing of errors was previously active.

suppress_errors( $suppress = true )   X-Ref
Enables or disables suppressing of database errors.

By default database errors are suppressed.

param: bool $suppress Optional. Whether to suppress errors. Default true.
return: bool Whether suppressing of errors was previously active.

flush()   X-Ref
Kills cached query results.


db_connect( $allow_bail = true )   X-Ref
Connects to and selects database.

If `$allow_bail` is false, the lack of database connection will need to be handled manually.

param: bool $allow_bail Optional. Allows the function to bail. Default true.
return: bool True with a successful connection, false on failure.

parse_db_host( $host )   X-Ref
Parses the DB_HOST setting to interpret it for mysqli_real_connect().

mysqli_real_connect() doesn't support the host param including a port or socket
like mysql_connect() does. This duplicates how mysql_connect() detects a port
and/or socket file.

param: string $host The DB_HOST setting to parse.
return: array|false {

check_connection( $allow_bail = true )   X-Ref
Checks that the connection to the database is still up. If not, try to reconnect.

If this function is unable to reconnect, it will forcibly die, or if called
after the {@see 'template_redirect'} hook has been fired, return false instead.

If `$allow_bail` is false, the lack of database connection will need to be handled manually.

param: bool $allow_bail Optional. Allows the function to bail. Default true.
return: bool|void True if the connection is up.

query( $query )   X-Ref
Performs a database query, using current database connection.

More information can be found on the documentation page.

param: string $query Database query.
return: int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows

_do_query( $query )   X-Ref
Internal function to perform the mysqli_query() call.

param: string $query The query to run.

log_query( $query, $query_time, $query_callstack, $query_start, $query_data )   X-Ref
Logs query data.

param: string $query           The query's SQL.
param: float  $query_time      Total time spent on the query, in seconds.
param: string $query_callstack Comma-separated list of the calling functions.
param: float  $query_start     Unix timestamp of the time at the start of the query.
param: array  $query_data      Custom query data.

placeholder_escape()   X-Ref
Generates and returns a placeholder escape string for use in queries returned by ::prepare().

return: string String to escape placeholders.

add_placeholder_escape( $query )   X-Ref
Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.

param: string $query The query to escape.
return: string The query with the placeholder escape string inserted where necessary.

remove_placeholder_escape( $query )   X-Ref
Removes the placeholder escape strings from a query.

param: string $query The query from which the placeholder will be removed.
return: string The query with the placeholder removed.

insert( $table, $data, $format = null )   X-Ref
Inserts a row into the table.

Examples:

$wpdb->insert(
'table',
array(
'column1' => 'foo',
'column2' => 'bar',
)
);
$wpdb->insert(
'table',
array(
'column1' => 'foo',
'column2' => 1337,
),
array(
'%s',
'%d',
)
);

param: string          $table  Table name.
param: array           $data   Data to insert (in column => value pairs).
param: string[]|string $format Optional. An array of formats to be mapped to each of the value in `$data`.
return: int|false The number of rows inserted, or false on error.

replace( $table, $data, $format = null )   X-Ref
Replaces a row in the table or inserts it if it does not exist, based on a PRIMARY KEY or a UNIQUE index.

A REPLACE works exactly like an INSERT, except that if an old row in the table has the same value as a new row
for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

Examples:

$wpdb->replace(
'table',
array(
'ID'      => 123,
'column1' => 'foo',
'column2' => 'bar',
)
);
$wpdb->replace(
'table',
array(
'ID'      => 456,
'column1' => 'foo',
'column2' => 1337,
),
array(
'%d',
'%s',
'%d',
)
);

param: string          $table  Table name.
param: array           $data   Data to insert (in column => value pairs).
param: string[]|string $format Optional. An array of formats to be mapped to each of the value in `$data`.
return: int|false The number of rows affected, or false on error.

_insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' )   X-Ref
Helper function for insert and replace.

Runs an insert or replace query based on `$type` argument.

param: string          $table  Table name.
param: array           $data   Data to insert (in column => value pairs).
param: string[]|string $format Optional. An array of formats to be mapped to each of the value in `$data`.
param: string          $type   Optional. Type of operation. Either 'INSERT' or 'REPLACE'.
return: int|false The number of rows affected, or false on error.

update( $table, $data, $where, $format = null, $where_format = null )   X-Ref
Updates a row in the table.

Examples:

$wpdb->update(
'table',
array(
'column1' => 'foo',
'column2' => 'bar',
),
array(
'ID' => 1,
)
);
$wpdb->update(
'table',
array(
'column1' => 'foo',
'column2' => 1337,
),
array(
'ID' => 1,
),
array(
'%s',
'%d',
),
array(
'%d',
)
);

param: string       $table           Table name.
param: array        $data            Data to update (in column => value pairs).
param: array        $where           A named array of WHERE clauses (in column => value pairs).
param: string[]|string $format       Optional. An array of formats to be mapped to each of the values in $data.
param: string[]|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
return: int|false The number of rows updated, or false on error.

delete( $table, $where, $where_format = null )   X-Ref
Deletes a row in the table.

Examples:

$wpdb->delete(
'table',
array(
'ID' => 1,
)
);
$wpdb->delete(
'table',
array(
'ID' => 1,
),
array(
'%d',
)
);

param: string          $table        Table name.
param: array           $where        A named array of WHERE clauses (in column => value pairs).
param: string[]|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
return: int|false The number of rows deleted, or false on error.

process_fields( $table, $data, $format )   X-Ref
Processes arrays of field/value pairs and field formats.

This is a helper method for wpdb's CRUD methods, which take field/value pairs
for inserts, updates, and where clauses. This method first pairs each value
with a format. Then it determines the charset of that field, using that
to determine if any invalid text would be stripped. If text is stripped,
then field processing is rejected and the query fails.

param: string          $table  Table name.
param: array           $data   Array of values keyed by their field names.
param: string[]|string $format Formats or format to be mapped to the values in the data.
return: array|false An array of fields that contain paired value and formats.

process_field_formats( $data, $format )   X-Ref
Prepares arrays of value/format pairs as passed to wpdb CRUD methods.

param: array           $data   Array of values keyed by their field names.
param: string[]|string $format Formats or format to be mapped to the values in the data.
return: array {

process_field_charsets( $data, $table )   X-Ref
Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats().

param: array $data {
param: string $table Table name.
return: array|false {

process_field_lengths( $data, $table )   X-Ref
For string fields, records the maximum string length that field can safely save.

param: array $data {
param: string $table Table name.
return: array|false {

get_var( $query = null, $x = 0, $y = 0 )   X-Ref
Retrieves one value from the database.

Executes a SQL query and returns the value from the SQL result.
If the SQL result contains more than one column and/or more than one row,
the value in the column and row specified is returned. If $query is null,
the value in the specified column and row from the previous SQL result is returned.

param: string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
param: int         $x     Optional. Column of value to return. Indexed from 0. Default 0.
param: int         $y     Optional. Row of value to return. Indexed from 0. Default 0.
return: string|null Database query result (as string), or null on failure.

get_row( $query = null, $output = OBJECT, $y = 0 )   X-Ref
Retrieves one row from the database.

Executes a SQL query and returns the row from the SQL result.

param: string|null $query  SQL query.
param: string      $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
param: int         $y      Optional. Row to return. Indexed from 0. Default 0.
return: array|object|null|void Database query result in format specified by $output or null on failure.

get_col( $query = null, $x = 0 )   X-Ref
Retrieves one column from the database.

Executes a SQL query and returns the column from the SQL result.
If the SQL result contains more than one column, the column specified is returned.
If $query is null, the specified column from the previous SQL result is returned.

param: string|null $query Optional. SQL query. Defaults to previous query.
param: int         $x     Optional. Column to return. Indexed from 0. Default 0.
return: array Database query result. Array indexed from 0 by SQL result row number.

get_results( $query = null, $output = OBJECT )   X-Ref
Retrieves an entire SQL result set from the database (i.e., many rows).

Executes a SQL query and returns the entire SQL result.

param: string $query  SQL query.
param: string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
return: array|object|null Database query results.

get_table_charset( $table )   X-Ref
Retrieves the character set for the given table.

param: string $table Table name.
return: string|WP_Error Table character set, WP_Error object if it couldn't be found.

get_col_charset( $table, $column )   X-Ref
Retrieves the character set for the given column.

param: string $table  Table name.
param: string $column Column name.
return: string|false|WP_Error Column character set as a string. False if the column has

get_col_length( $table, $column )   X-Ref
Retrieves the maximum string length allowed in a given column.

The length may either be specified as a byte length or a character length.

param: string $table  Table name.
param: string $column Column name.
return: array|false|WP_Error {

check_ascii( $input_string )   X-Ref
Checks if a string is ASCII.

The negative regex is faster for non-ASCII strings, as it allows
the search to finish as soon as it encounters a non-ASCII character.

param: string $input_string String to check.
return: bool True if ASCII, false if not.

check_safe_collation( $query )   X-Ref
Checks if the query is accessing a collation considered safe on the current version of MySQL.

param: string $query The query to check.
return: bool True if the collation is safe, false if it isn't.

strip_invalid_text( $data )   X-Ref
Strips any invalid characters based on value/charset pairs.

param: array $data Array of value arrays. Each value array has the keys 'value', 'charset', and 'length'.
return: array|WP_Error The $data parameter, with invalid characters removed from each value.

strip_invalid_text_from_query( $query )   X-Ref
Strips any invalid characters from the query.

param: string $query Query to convert.
return: string|WP_Error The converted query, or a WP_Error object if the conversion fails.

strip_invalid_text_for_column( $table, $column, $value )   X-Ref
Strips any invalid characters from the string for a given table and column.

param: string $table  Table name.
param: string $column Column name.
param: string $value  The text to check.
return: string|WP_Error The converted string, or a WP_Error object if the conversion fails.

get_table_from_query( $query )   X-Ref
Finds the first table name referenced in a query.

param: string $query The query to search.
return: string|false The table name found, or false if a table couldn't be found.

load_col_info()   X-Ref
Loads the column metadata from the last query.


get_col_info( $info_type = 'name', $col_offset = -1 )   X-Ref
Retrieves column metadata from the last query.

param: string $info_type  Optional. Possible values include 'name', 'table', 'def', 'max_length',
param: int    $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length.
return: mixed Column results.

timer_start()   X-Ref
Starts the timer, for debugging purposes.

return: true

timer_stop()   X-Ref
Stops the debugging timer.

return: float Total time spent on the query, in seconds.

bail( $message, $error_code = '500' )   X-Ref
Wraps errors in a nice header and footer and dies.

Will not die if wpdb::$show_errors is false.

param: string $message    The error message.
param: string $error_code Optional. A computer-readable string to identify the error.
return: void|false Void if the showing of errors is enabled, false if disabled.

close()   X-Ref
Closes the current database connection.

return: bool True if the connection was successfully closed,

check_database_version()   X-Ref
Determines whether MySQL database is at least the required minimum version.

return: void|WP_Error

supports_collation()   X-Ref
Determines whether the database supports collation.

Called when WordPress is generating the table scheme.

Use `wpdb::has_cap( 'collation' )`.

return: bool True if collation is supported, false if not.

get_charset_collate()   X-Ref
Retrieves the database character collate.

return: string The database character collate.

has_cap( $db_cap )   X-Ref
Determines whether the database or WPDB supports a particular feature.

Capability sniffs for the database server and current version of WPDB.

Database sniffs are based on the version of MySQL the site is using.

WPDB sniffs are added as new features are introduced to allow theme and plugin
developers to determine feature support. This is to account for drop-ins which may
introduce feature support at a different time to WordPress.

param: string $db_cap The feature to check for. Accepts 'collation', 'group_concat',
return: bool True when the database feature is supported, false otherwise.

get_caller()   X-Ref
Retrieves a comma-separated list of the names of the functions that called wpdb.

return: string Comma-separated list of the calling functions.

db_version()   X-Ref
Retrieves the database server version.

return: string|null Version number on success, null on failure.

db_server_info()   X-Ref
Returns the version of the MySQL server.

return: string Server version as a string.



Generated : Thu Nov 21 08:20:01 2024 Cross-referenced by PHPXref