5 * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
15 define( 'EZSQL_VERSION', 'WP1.25' );
20 define( 'OBJECT', 'OBJECT' );
21 define( 'object', 'OBJECT' ); // Back compat.
26 define( 'OBJECT_K', 'OBJECT_K' );
31 define( 'ARRAY_A', 'ARRAY_A' );
36 define( 'ARRAY_N', 'ARRAY_N' );
39 * WordPress Database Access Abstraction Object
41 * It is possible to replace this class with your own
42 * by setting the $wpdb global variable in wp-content/db.php
43 * file to your class. The wpdb class will still be included,
44 * so you can extend it or simply use your own.
46 * @link https://codex.wordpress.org/Function_Reference/wpdb_Class
49 * @subpackage Database
55 * Whether to show SQL/DB errors.
57 * Default behavior is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY
64 var $show_errors = false;
67 * Whether to suppress errors during the DB bootstrapping.
73 var $suppress_errors = false;
76 * The last error during query.
81 public $last_error = '';
84 * Amount of queries made
90 public $num_queries = 0;
93 * Count of rows returned by previous query
102 * Count of affected rows by previous query
108 var $rows_affected = 0;
111 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
117 public $insert_id = 0;
129 * Results of the last query made
138 * MySQL result, which is either a resource or boolean.
147 * Cached column info, for sanity checking data before inserting
153 protected $col_meta = array();
156 * Calculated character sets on tables
162 protected $table_charset = array();
165 * Whether text fields in the current query need to be sanity checked.
171 protected $check_current_query = true;
174 * Flag to ensure we don't run into recursion problems when checking the collation.
178 * @see wpdb::check_safe_collation()
181 private $checking_collation = false;
184 * Saved info on the table column
193 * Saved queries that were executed
202 * The number of times to retry reconnecting before dying.
206 * @see wpdb::check_connection()
209 protected $reconnect_retries = 5;
212 * WordPress table prefix
214 * You can set this to have multiple WordPress installations
215 * in a single database. The second reason is for possible
216 * security precautions.
225 * WordPress base table prefix.
234 * Whether the database queries are ready to start executing.
261 * List of WordPress per-blog tables
265 * @see wpdb::tables()
268 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
269 'terms', 'term_taxonomy', 'term_relationships', 'termmeta', 'commentmeta' );
272 * List of deprecated WordPress tables
274 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
278 * @see wpdb::tables()
281 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
284 * List of WordPress global tables
288 * @see wpdb::tables()
291 var $global_tables = array( 'users', 'usermeta' );
294 * List of Multisite global tables
298 * @see wpdb::tables()
301 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
302 'sitecategories', 'registration_log', 'blog_versions' );
305 * WordPress Comments table
314 * WordPress Comment Metadata table
323 * WordPress Links table
332 * WordPress Options table
341 * WordPress Post Metadata table
350 * WordPress Posts table
359 * WordPress Terms table
368 * WordPress Term Relationships table
374 public $term_relationships;
377 * WordPress Term Taxonomy table
383 public $term_taxonomy;
386 * WordPress Term Meta table.
395 // Global and Multisite tables
399 * WordPress User Metadata table
408 * WordPress Users table
417 * Multisite Blogs table
426 * Multisite Blog Versions table
432 public $blog_versions;
435 * Multisite Registration Log table
441 public $registration_log;
444 * Multisite Signups table
453 * Multisite Sites table
462 * Multisite Sitewide Terms table
468 public $sitecategories;
471 * Multisite Site Metadata table
480 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
482 * Keys are column names, values are format types: 'ID' => '%d'
485 * @see wpdb::prepare()
486 * @see wpdb::insert()
487 * @see wpdb::update()
488 * @see wpdb::delete()
489 * @see wp_set_wpdb_vars()
493 public $field_types = array();
496 * Database table columns charset
505 * Database table columns collate
529 protected $dbpassword;
559 * A textual description of the last query/get_row/get_var call
568 * Whether MySQL is used as the database engine.
570 * Set in WPDB::db_connect() to true, by default. This is used when checking
571 * against the required MySQL version for WordPress. Normally, a replacement
572 * database drop-in (db.php) will skip these checks, but setting this to true
573 * will force the checks to occur.
579 public $is_mysql = null;
582 * A list of incompatible SQL modes.
588 protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
589 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
592 * Whether to use mysqli over mysql.
598 private $use_mysqli = false;
601 * Whether we've managed to successfully connect at some point
607 private $has_connected = false;
610 * Connects to the database server and selects a database
612 * PHP5 style constructor for compatibility with PHP5. Does
613 * the actual setting up of the class properties and connection
616 * @link https://core.trac.wordpress.org/ticket/3354
619 * @global string $wp_version
621 * @param string $dbuser MySQL database user
622 * @param string $dbpassword MySQL database password
623 * @param string $dbname MySQL database name
624 * @param string $dbhost MySQL database host
626 public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
627 register_shutdown_function( array( $this, '__destruct' ) );
629 if ( WP_DEBUG && WP_DEBUG_DISPLAY )
630 $this->show_errors();
632 /* Use ext/mysqli if it exists and:
633 * - WP_USE_EXT_MYSQL is defined as false, or
634 * - We are a development version of WordPress, or
635 * - We are running PHP 5.5 or greater, or
636 * - ext/mysql is not loaded.
638 if ( function_exists( 'mysqli_connect' ) ) {
639 if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
640 $this->use_mysqli = ! WP_USE_EXT_MYSQL;
641 } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
642 $this->use_mysqli = true;
643 } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
644 $this->use_mysqli = true;
648 $this->dbuser = $dbuser;
649 $this->dbpassword = $dbpassword;
650 $this->dbname = $dbname;
651 $this->dbhost = $dbhost;
653 // wp-config.php creation will manually connect when ready.
654 if ( defined( 'WP_SETUP_CONFIG' ) ) {
662 * PHP5 style destructor and will run when database object is destroyed.
664 * @see wpdb::__construct()
668 public function __destruct() {
673 * Makes private properties readable for backward compatibility.
677 * @param string $name The private member to get, and optionally process
678 * @return mixed The private member
680 public function __get( $name ) {
681 if ( 'col_info' === $name )
682 $this->load_col_info();
688 * Makes private properties settable for backward compatibility.
692 * @param string $name The private member to set
693 * @param mixed $value The value to set
695 public function __set( $name, $value ) {
696 $protected_members = array(
699 'check_current_query',
701 if ( in_array( $name, $protected_members, true ) ) {
704 $this->$name = $value;
708 * Makes private properties check-able for backward compatibility.
712 * @param string $name The private member to check
714 * @return bool If the member is set or not
716 public function __isset( $name ) {
717 return isset( $this->$name );
721 * Makes private properties un-settable for backward compatibility.
725 * @param string $name The private member to unset
727 public function __unset( $name ) {
728 unset( $this->$name );
732 * Set $this->charset and $this->collate
736 public function init_charset() {
740 if ( function_exists('is_multisite') && is_multisite() ) {
742 if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
743 $collate = DB_COLLATE;
745 $collate = 'utf8_general_ci';
747 } elseif ( defined( 'DB_COLLATE' ) ) {
748 $collate = DB_COLLATE;
751 if ( defined( 'DB_CHARSET' ) ) {
752 $charset = DB_CHARSET;
755 $charset_collate = $this->determine_charset( $charset, $collate );
757 $this->charset = $charset_collate['charset'];
758 $this->collate = $charset_collate['collate'];
762 * Determines the best charset and collation to use given a charset and collation.
764 * For example, when able, utf8mb4 should be used instead of utf8.
769 * @param string $charset The character set to check.
770 * @param string $collate The collation to check.
771 * @return array The most appropriate character set and collation to use.
773 public function determine_charset( $charset, $collate ) {
774 if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
775 return compact( 'charset', 'collate' );
778 if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
779 $charset = 'utf8mb4';
782 if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
784 $collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
787 if ( 'utf8mb4' === $charset ) {
788 // _general_ is outdated, so we can upgrade it to _unicode_, instead.
789 if ( ! $collate || 'utf8_general_ci' === $collate ) {
790 $collate = 'utf8mb4_unicode_ci';
792 $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
796 // _unicode_520_ is a better collation, we should use that when it's available.
797 if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
798 $collate = 'utf8mb4_unicode_520_ci';
801 return compact( 'charset', 'collate' );
805 * Sets the connection's character set.
809 * @param resource $dbh The resource given by mysql_connect
810 * @param string $charset Optional. The character set. Default null.
811 * @param string $collate Optional. The collation. Default null.
813 public function set_charset( $dbh, $charset = null, $collate = null ) {
814 if ( ! isset( $charset ) )
815 $charset = $this->charset;
816 if ( ! isset( $collate ) )
817 $collate = $this->collate;
818 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
819 $set_charset_succeeded = true;
821 if ( $this->use_mysqli ) {
822 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
823 $set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
826 if ( $set_charset_succeeded ) {
827 $query = $this->prepare( 'SET NAMES %s', $charset );
828 if ( ! empty( $collate ) )
829 $query .= $this->prepare( ' COLLATE %s', $collate );
830 mysqli_query( $dbh, $query );
833 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
834 $set_charset_succeeded = mysql_set_charset( $charset, $dbh );
836 if ( $set_charset_succeeded ) {
837 $query = $this->prepare( 'SET NAMES %s', $charset );
838 if ( ! empty( $collate ) )
839 $query .= $this->prepare( ' COLLATE %s', $collate );
840 mysql_query( $query, $dbh );
847 * Change the current SQL mode, and ensure its WordPress compatibility.
849 * If no modes are passed, it will ensure the current MySQL server
850 * modes are compatible.
854 * @param array $modes Optional. A list of SQL modes to set.
856 public function set_sql_mode( $modes = array() ) {
857 if ( empty( $modes ) ) {
858 if ( $this->use_mysqli ) {
859 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
861 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
864 if ( empty( $res ) ) {
868 if ( $this->use_mysqli ) {
869 $modes_array = mysqli_fetch_array( $res );
870 if ( empty( $modes_array[0] ) ) {
873 $modes_str = $modes_array[0];
875 $modes_str = mysql_result( $res, 0 );
878 if ( empty( $modes_str ) ) {
882 $modes = explode( ',', $modes_str );
885 $modes = array_change_key_case( $modes, CASE_UPPER );
888 * Filters the list of incompatible SQL modes to exclude.
892 * @param array $incompatible_modes An array of incompatible modes.
894 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
896 foreach ( $modes as $i => $mode ) {
897 if ( in_array( $mode, $incompatible_modes ) ) {
898 unset( $modes[ $i ] );
902 $modes_str = implode( ',', $modes );
904 if ( $this->use_mysqli ) {
905 mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
907 mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
912 * Sets the table prefix for the WordPress tables.
916 * @param string $prefix Alphanumeric name for the new prefix.
917 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
918 * @return string|WP_Error Old prefix or WP_Error on error
920 public function set_prefix( $prefix, $set_table_names = true ) {
922 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
923 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
925 $old_prefix = is_multisite() ? '' : $prefix;
927 if ( isset( $this->base_prefix ) )
928 $old_prefix = $this->base_prefix;
930 $this->base_prefix = $prefix;
932 if ( $set_table_names ) {
933 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
934 $this->$table = $prefixed_table;
936 if ( is_multisite() && empty( $this->blogid ) )
939 $this->prefix = $this->get_blog_prefix();
941 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
942 $this->$table = $prefixed_table;
944 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
945 $this->$table = $prefixed_table;
956 * @param int $blog_id
957 * @param int $site_id Optional.
958 * @return int previous blog id
960 public function set_blog_id( $blog_id, $site_id = 0 ) {
961 if ( ! empty( $site_id ) )
962 $this->siteid = $site_id;
964 $old_blog_id = $this->blogid;
965 $this->blogid = $blog_id;
967 $this->prefix = $this->get_blog_prefix();
969 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
970 $this->$table = $prefixed_table;
972 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
973 $this->$table = $prefixed_table;
982 * @param int $blog_id Optional.
983 * @return string Blog prefix.
985 public function get_blog_prefix( $blog_id = null ) {
986 if ( is_multisite() ) {
987 if ( null === $blog_id )
988 $blog_id = $this->blogid;
989 $blog_id = (int) $blog_id;
990 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
991 return $this->base_prefix;
993 return $this->base_prefix . $blog_id . '_';
995 return $this->base_prefix;
1000 * Returns an array of WordPress tables.
1002 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
1003 * override the WordPress users and usermeta tables that would otherwise
1004 * be determined by the prefix.
1006 * The scope argument can take one of the following:
1008 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
1009 * 'blog' - returns the blog-level tables for the queried blog.
1010 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
1011 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
1012 * 'old' - returns tables which are deprecated.
1015 * @uses wpdb::$tables
1016 * @uses wpdb::$old_tables
1017 * @uses wpdb::$global_tables
1018 * @uses wpdb::$ms_global_tables
1020 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
1021 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
1022 * prefix is requested, then the custom users and usermeta tables will be mapped.
1023 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
1024 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
1026 public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
1029 $tables = array_merge( $this->global_tables, $this->tables );
1030 if ( is_multisite() )
1031 $tables = array_merge( $tables, $this->ms_global_tables );
1034 $tables = $this->tables;
1037 $tables = $this->global_tables;
1038 if ( is_multisite() )
1039 $tables = array_merge( $tables, $this->ms_global_tables );
1042 $tables = $this->ms_global_tables;
1045 $tables = $this->old_tables;
1053 $blog_id = $this->blogid;
1054 $blog_prefix = $this->get_blog_prefix( $blog_id );
1055 $base_prefix = $this->base_prefix;
1056 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
1057 foreach ( $tables as $k => $table ) {
1058 if ( in_array( $table, $global_tables ) )
1059 $tables[ $table ] = $base_prefix . $table;
1061 $tables[ $table ] = $blog_prefix . $table;
1062 unset( $tables[ $k ] );
1065 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
1066 $tables['users'] = CUSTOM_USER_TABLE;
1068 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
1069 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
1076 * Selects a database using the current database connection.
1078 * The database name will be changed based on the current database
1079 * connection. On failure, the execution will bail and display an DB error.
1083 * @param string $db MySQL database name
1084 * @param resource|null $dbh Optional link identifier.
1086 public function select( $db, $dbh = null ) {
1087 if ( is_null($dbh) )
1090 if ( $this->use_mysqli ) {
1091 $success = mysqli_select_db( $dbh, $db );
1093 $success = mysql_select_db( $db, $dbh );
1096 $this->ready = false;
1097 if ( ! did_action( 'template_redirect' ) ) {
1098 wp_load_translations_early();
1100 $message = '<h1>' . __( 'Can’t select database' ) . "</h1>\n";
1102 $message .= '<p>' . sprintf(
1103 /* translators: %s: database name */
1104 __( 'We were able to connect to the database server (which means your username and password is okay) but not able to select the %s database.' ),
1105 '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1108 $message .= "<ul>\n";
1109 $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
1111 $message .= '<li>' . sprintf(
1112 /* translators: 1: database user, 2: database name */
1113 __( 'Does the user %1$s have permission to use the %2$s database?' ),
1114 '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
1115 '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1118 $message .= '<li>' . sprintf(
1119 /* translators: %s: database name */
1120 __( 'On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?' ),
1121 htmlspecialchars( $db, ENT_QUOTES )
1124 $message .= "</ul>\n";
1126 $message .= '<p>' . sprintf(
1127 /* translators: %s: support forums URL */
1128 __( 'If you don’t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="%s">WordPress Support Forums</a>.' ),
1129 __( 'https://wordpress.org/support/' )
1132 $this->bail( $message, 'db_select_fail' );
1138 * Do not use, deprecated.
1140 * Use esc_sql() or wpdb::prepare() instead.
1143 * @deprecated 3.6.0 Use wpdb::prepare()
1144 * @see wpdb::prepare
1148 * @param string $string
1151 function _weak_escape( $string ) {
1152 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1153 _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
1154 return addslashes( $string );
1158 * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1160 * @see mysqli_real_escape_string()
1161 * @see mysql_real_escape_string()
1165 * @param string $string to escape
1166 * @return string escaped
1168 function _real_escape( $string ) {
1170 if ( $this->use_mysqli ) {
1171 return mysqli_real_escape_string( $this->dbh, $string );
1173 return mysql_real_escape_string( $string, $this->dbh );
1177 $class = get_class( $this );
1178 if ( function_exists( '__' ) ) {
1179 /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
1180 _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
1182 _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
1184 return addslashes( $string );
1188 * Escape data. Works on arrays.
1190 * @uses wpdb::_real_escape()
1194 * @param string|array $data
1195 * @return string|array escaped
1197 function _escape( $data ) {
1198 if ( is_array( $data ) ) {
1199 foreach ( $data as $k => $v ) {
1201 $data[$k] = $this->_escape( $v );
1203 $data[$k] = $this->_real_escape( $v );
1206 $data = $this->_real_escape( $data );
1213 * Do not use, deprecated.
1215 * Use esc_sql() or wpdb::prepare() instead.
1218 * @deprecated 3.6.0 Use wpdb::prepare()
1219 * @see wpdb::prepare()
1222 * @param mixed $data
1225 public function escape( $data ) {
1226 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1227 _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
1228 if ( is_array( $data ) ) {
1229 foreach ( $data as $k => $v ) {
1230 if ( is_array( $v ) )
1231 $data[$k] = $this->escape( $v, 'recursive' );
1233 $data[$k] = $this->_weak_escape( $v, 'internal' );
1236 $data = $this->_weak_escape( $data, 'internal' );
1243 * Escapes content by reference for insertion into the database, for security
1245 * @uses wpdb::_real_escape()
1249 * @param string $string to escape
1251 public function escape_by_ref( &$string ) {
1252 if ( ! is_float( $string ) )
1253 $string = $this->_real_escape( $string );
1257 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1259 * The following directives can be used in the query format string:
1263 * %% (literal percentage sign - no argument needed)
1265 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1266 * Literals (%) as parts of the query must be properly written as %%.
1268 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1269 * Does not support sign, padding, alignment, width or precision specifiers.
1270 * Does not support argument numbering/swapping.
1272 * May be called like {@link https://secure.php.net/sprintf sprintf()} or like {@link https://secure.php.net/vsprintf vsprintf()}.
1274 * Both %d and %s should be left unquoted in the query string.
1276 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1277 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1279 * @link https://secure.php.net/sprintf Description of syntax.
1282 * @param string $query Query statement with sprintf()-like placeholders
1283 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1284 * {@link https://secure.php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1285 * being called like {@link https://secure.php.net/sprintf sprintf()}.
1286 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1287 * {@link https://secure.php.net/sprintf sprintf()}.
1288 * @return string|void Sanitized query string, if there is a query to prepare.
1290 public function prepare( $query, $args ) {
1291 if ( is_null( $query ) )
1294 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1295 if ( strpos( $query, '%' ) === false ) {
1296 _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
1299 $args = func_get_args();
1300 array_shift( $args );
1301 // If args were passed as an array (as in vsprintf), move them up
1302 if ( isset( $args[0] ) && is_array($args[0]) )
1304 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1305 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1306 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1307 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1308 array_walk( $args, array( $this, 'escape_by_ref' ) );
1309 return @vsprintf( $query, $args );
1313 * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1315 * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1317 * Example Prepared Statement:
1320 * $find = 'only 43% of planets';
1321 * $like = $wild . $wpdb->esc_like( $find ) . $wild;
1322 * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE '%s'", $like );
1324 * Example Escape Chain:
1326 * $sql = esc_sql( $wpdb->esc_like( $input ) );
1331 * @param string $text The raw text to be escaped. The input typed by the user should have no
1332 * extra or deleted slashes.
1333 * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1334 * or real_escape next.
1336 public function esc_like( $text ) {
1337 return addcslashes( $text, '_%\\' );
1341 * Print SQL/DB error.
1344 * @global array $EZSQL_ERROR Stores error information of query and error string
1346 * @param string $str The error to display
1347 * @return false|void False if the showing of errors is disabled.
1349 public function print_error( $str = '' ) {
1350 global $EZSQL_ERROR;
1353 if ( $this->use_mysqli ) {
1354 $str = mysqli_error( $this->dbh );
1356 $str = mysql_error( $this->dbh );
1359 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1361 if ( $this->suppress_errors )
1364 wp_load_translations_early();
1366 if ( $caller = $this->get_caller() )
1367 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1369 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1371 error_log( $error_str );
1373 // Are we showing errors?
1374 if ( ! $this->show_errors )
1377 // If there is an error then take note of it
1378 if ( is_multisite() ) {
1381 __( 'WordPress database error:' ),
1386 if ( defined( 'ERRORLOGFILE' ) ) {
1387 error_log( $msg, 3, ERRORLOGFILE );
1389 if ( defined( 'DIEONDBERROR' ) ) {
1393 $str = htmlspecialchars( $str, ENT_QUOTES );
1394 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1397 '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
1398 __( 'WordPress database error:' ),
1406 * Enables showing of database errors.
1408 * This function should be used only to enable showing of errors.
1409 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1410 * this function can be used to enable and disable showing of database
1414 * @see wpdb::hide_errors()
1416 * @param bool $show Whether to show or hide errors
1417 * @return bool Old value for showing errors.
1419 public function show_errors( $show = true ) {
1420 $errors = $this->show_errors;
1421 $this->show_errors = $show;
1426 * Disables showing of database errors.
1428 * By default database errors are not shown.
1431 * @see wpdb::show_errors()
1433 * @return bool Whether showing of errors was active
1435 public function hide_errors() {
1436 $show = $this->show_errors;
1437 $this->show_errors = false;
1442 * Whether to suppress database errors.
1444 * By default database errors are suppressed, with a simple
1445 * call to this function they can be enabled.
1448 * @see wpdb::hide_errors()
1449 * @param bool $suppress Optional. New value. Defaults to true.
1450 * @return bool Old value
1452 public function suppress_errors( $suppress = true ) {
1453 $errors = $this->suppress_errors;
1454 $this->suppress_errors = (bool) $suppress;
1459 * Kill cached query results.
1463 public function flush() {
1464 $this->last_result = array();
1465 $this->col_info = null;
1466 $this->last_query = null;
1467 $this->rows_affected = $this->num_rows = 0;
1468 $this->last_error = '';
1470 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1471 mysqli_free_result( $this->result );
1472 $this->result = null;
1474 // Sanity check before using the handle
1475 if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1479 // Clear out any results from a multi-query
1480 while ( mysqli_more_results( $this->dbh ) ) {
1481 mysqli_next_result( $this->dbh );
1483 } elseif ( is_resource( $this->result ) ) {
1484 mysql_free_result( $this->result );
1489 * Connect to and select database.
1491 * If $allow_bail is false, the lack of database connection will need
1492 * to be handled manually.
1495 * @since 3.9.0 $allow_bail parameter added.
1497 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1498 * @return bool True with a successful connection, false on failure.
1500 public function db_connect( $allow_bail = true ) {
1501 $this->is_mysql = true;
1504 * Deprecated in 3.9+ when using MySQLi. No equivalent
1505 * $new_link parameter exists for mysqli_* functions.
1507 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1508 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1510 if ( $this->use_mysqli ) {
1511 $this->dbh = mysqli_init();
1513 // mysqli_real_connect doesn't support the host param including a port or socket
1514 // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1517 $host = $this->dbhost;
1518 $port_or_socket = strstr( $host, ':' );
1519 if ( ! empty( $port_or_socket ) ) {
1520 $host = substr( $host, 0, strpos( $host, ':' ) );
1521 $port_or_socket = substr( $port_or_socket, 1 );
1522 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1523 $port = intval( $port_or_socket );
1524 $maybe_socket = strstr( $port_or_socket, ':' );
1525 if ( ! empty( $maybe_socket ) ) {
1526 $socket = substr( $maybe_socket, 1 );
1529 $socket = $port_or_socket;
1534 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1536 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1539 if ( $this->dbh->connect_errno ) {
1542 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1543 * - We haven't previously connected, and
1544 * - WP_USE_EXT_MYSQL isn't set to false, and
1545 * - ext/mysql is loaded.
1547 $attempt_fallback = true;
1549 if ( $this->has_connected ) {
1550 $attempt_fallback = false;
1551 } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1552 $attempt_fallback = false;
1553 } elseif ( ! function_exists( 'mysql_connect' ) ) {
1554 $attempt_fallback = false;
1557 if ( $attempt_fallback ) {
1558 $this->use_mysqli = false;
1559 return $this->db_connect( $allow_bail );
1564 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1566 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1570 if ( ! $this->dbh && $allow_bail ) {
1571 wp_load_translations_early();
1573 // Load custom DB error template, if present.
1574 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1575 require_once( WP_CONTENT_DIR . '/db-error.php' );
1579 $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
1581 $message .= '<p>' . sprintf(
1582 /* translators: 1: wp-config.php. 2: database host */
1583 __( 'This either means that the username and password information in your %1$s file is incorrect or we can’t contact the database server at %2$s. This could mean your host’s database server is down.' ),
1584 '<code>wp-config.php</code>',
1585 '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1588 $message .= "<ul>\n";
1589 $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
1590 $message .= '<li>' . __( 'Are you sure that you have typed the correct hostname?' ) . "</li>\n";
1591 $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1592 $message .= "</ul>\n";
1594 $message .= '<p>' . sprintf(
1595 /* translators: %s: support forums URL */
1596 __( 'If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
1597 __( 'https://wordpress.org/support/' )
1600 $this->bail( $message, 'db_connect_fail' );
1603 } elseif ( $this->dbh ) {
1604 if ( ! $this->has_connected ) {
1605 $this->init_charset();
1608 $this->has_connected = true;
1610 $this->set_charset( $this->dbh );
1612 $this->ready = true;
1613 $this->set_sql_mode();
1614 $this->select( $this->dbname, $this->dbh );
1623 * Checks that the connection to the database is still up. If not, try to reconnect.
1625 * If this function is unable to reconnect, it will forcibly die, or if after the
1626 * the {@see 'template_redirect'} hook has been fired, return false instead.
1628 * If $allow_bail is false, the lack of database connection will need
1629 * to be handled manually.
1633 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1634 * @return bool|void True if the connection is up.
1636 public function check_connection( $allow_bail = true ) {
1637 if ( $this->use_mysqli ) {
1638 if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
1642 if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
1647 $error_reporting = false;
1649 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1651 $error_reporting = error_reporting();
1652 error_reporting( $error_reporting & ~E_WARNING );
1655 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1656 // On the last try, re-enable warnings. We want to see a single instance of the
1657 // "unable to connect" message on the bail() screen, if it appears.
1658 if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1659 error_reporting( $error_reporting );
1662 if ( $this->db_connect( false ) ) {
1663 if ( $error_reporting ) {
1664 error_reporting( $error_reporting );
1673 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1674 // Let's just return and hope for the best.
1675 if ( did_action( 'template_redirect' ) ) {
1679 if ( ! $allow_bail ) {
1683 wp_load_translations_early();
1685 $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
1687 $message .= '<p>' . sprintf(
1688 /* translators: %s: database host */
1689 __( 'This means that we lost contact with the database server at %s. This could mean your host’s database server is down.' ),
1690 '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1693 $message .= "<ul>\n";
1694 $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1695 $message .= '<li>' . __( 'Are you sure that the database server is not under particularly heavy load?' ) . "</li>\n";
1696 $message .= "</ul>\n";
1698 $message .= '<p>' . sprintf(
1699 /* translators: %s: support forums URL */
1700 __( 'If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
1701 __( 'https://wordpress.org/support/' )
1704 // We weren't able to reconnect, so we better bail.
1705 $this->bail( $message, 'db_connect_fail' );
1707 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1712 * Perform a MySQL database query, using current database connection.
1714 * More information can be found on the codex page.
1718 * @param string $query Database query
1719 * @return int|false Number of rows affected/selected or false on error
1721 public function query( $query ) {
1722 if ( ! $this->ready ) {
1723 $this->check_current_query = true;
1728 * Filters the database query.
1730 * Some queries are made before the plugins have been loaded,
1731 * and thus cannot be filtered with this method.
1735 * @param string $query Database query.
1737 $query = apply_filters( 'query', $query );
1741 // Log how the function was called
1742 $this->func_call = "\$db->query(\"$query\")";
1744 // If we're writing to the database, make sure the query will write safely.
1745 if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
1746 $stripped_query = $this->strip_invalid_text_from_query( $query );
1747 // strip_invalid_text_from_query() can perform queries, so we need
1748 // to flush again, just to make sure everything is clear.
1750 if ( $stripped_query !== $query ) {
1751 $this->insert_id = 0;
1756 $this->check_current_query = true;
1758 // Keep track of the last query for debug.
1759 $this->last_query = $query;
1761 $this->_do_query( $query );
1763 // MySQL server has gone away, try to reconnect.
1765 if ( ! empty( $this->dbh ) ) {
1766 if ( $this->use_mysqli ) {
1767 if ( $this->dbh instanceof mysqli ) {
1768 $mysql_errno = mysqli_errno( $this->dbh );
1770 // $dbh is defined, but isn't a real connection.
1771 // Something has gone horribly wrong, let's try a reconnect.
1772 $mysql_errno = 2006;
1775 if ( is_resource( $this->dbh ) ) {
1776 $mysql_errno = mysql_errno( $this->dbh );
1778 $mysql_errno = 2006;
1783 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1784 if ( $this->check_connection() ) {
1785 $this->_do_query( $query );
1787 $this->insert_id = 0;
1792 // If there is an error then take note of it.
1793 if ( $this->use_mysqli ) {
1794 if ( $this->dbh instanceof mysqli ) {
1795 $this->last_error = mysqli_error( $this->dbh );
1797 $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
1800 if ( is_resource( $this->dbh ) ) {
1801 $this->last_error = mysql_error( $this->dbh );
1803 $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
1807 if ( $this->last_error ) {
1808 // Clear insert_id on a subsequent failed insert.
1809 if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1810 $this->insert_id = 0;
1812 $this->print_error();
1816 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1817 $return_val = $this->result;
1818 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1819 if ( $this->use_mysqli ) {
1820 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1822 $this->rows_affected = mysql_affected_rows( $this->dbh );
1824 // Take note of the insert_id
1825 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1826 if ( $this->use_mysqli ) {
1827 $this->insert_id = mysqli_insert_id( $this->dbh );
1829 $this->insert_id = mysql_insert_id( $this->dbh );
1832 // Return number of rows affected
1833 $return_val = $this->rows_affected;
1836 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1837 while ( $row = mysqli_fetch_object( $this->result ) ) {
1838 $this->last_result[$num_rows] = $row;
1841 } elseif ( is_resource( $this->result ) ) {
1842 while ( $row = mysql_fetch_object( $this->result ) ) {
1843 $this->last_result[$num_rows] = $row;
1848 // Log number of rows the query returned
1849 // and return number of rows selected
1850 $this->num_rows = $num_rows;
1851 $return_val = $num_rows;
1858 * Internal function to perform the mysql_query() call.
1863 * @see wpdb::query()
1865 * @param string $query The query to run.
1867 private function _do_query( $query ) {
1868 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1869 $this->timer_start();
1872 if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
1873 $this->result = mysqli_query( $this->dbh, $query );
1874 } elseif ( ! empty( $this->dbh ) ) {
1875 $this->result = mysql_query( $query, $this->dbh );
1877 $this->num_queries++;
1879 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1880 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1885 * Insert a row into a table.
1887 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1888 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1891 * @see wpdb::prepare()
1892 * @see wpdb::$field_types
1893 * @see wp_set_wpdb_vars()
1895 * @param string $table Table name
1896 * @param array $data Data to insert (in column => value pairs).
1897 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1898 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1899 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1900 * If string, that format will be used for all of the values in $data.
1901 * A format is one of '%d', '%f', '%s' (integer, float, string).
1902 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1903 * @return int|false The number of rows inserted, or false on error.
1905 public function insert( $table, $data, $format = null ) {
1906 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1910 * Replace a row into a table.
1912 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1913 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1916 * @see wpdb::prepare()
1917 * @see wpdb::$field_types
1918 * @see wp_set_wpdb_vars()
1920 * @param string $table Table name
1921 * @param array $data Data to insert (in column => value pairs).
1922 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1923 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1924 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1925 * If string, that format will be used for all of the values in $data.
1926 * A format is one of '%d', '%f', '%s' (integer, float, string).
1927 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1928 * @return int|false The number of rows affected, or false on error.
1930 public function replace( $table, $data, $format = null ) {
1931 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1935 * Helper function for insert and replace.
1937 * Runs an insert or replace query based on $type argument.
1941 * @see wpdb::prepare()
1942 * @see wpdb::$field_types
1943 * @see wp_set_wpdb_vars()
1945 * @param string $table Table name
1946 * @param array $data Data to insert (in column => value pairs).
1947 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1948 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1949 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1950 * If string, that format will be used for all of the values in $data.
1951 * A format is one of '%d', '%f', '%s' (integer, float, string).
1952 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1953 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1954 * @return int|false The number of rows affected, or false on error.
1956 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1957 $this->insert_id = 0;
1959 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
1963 $data = $this->process_fields( $table, $data, $format );
1964 if ( false === $data ) {
1968 $formats = $values = array();
1969 foreach ( $data as $value ) {
1970 if ( is_null( $value['value'] ) ) {
1971 $formats[] = 'NULL';
1975 $formats[] = $value['format'];
1976 $values[] = $value['value'];
1979 $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
1980 $formats = implode( ', ', $formats );
1982 $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
1984 $this->check_current_query = false;
1985 return $this->query( $this->prepare( $sql, $values ) );
1989 * Update a row in the table
1991 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1992 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1995 * @see wpdb::prepare()
1996 * @see wpdb::$field_types
1997 * @see wp_set_wpdb_vars()
1999 * @param string $table Table name
2000 * @param array $data Data to update (in column => value pairs).
2001 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
2002 * Sending a null value will cause the column to be set to NULL - the corresponding
2003 * format is ignored in this case.
2004 * @param array $where A named array of WHERE clauses (in column => value pairs).
2005 * Multiple clauses will be joined with ANDs.
2006 * Both $where columns and $where values should be "raw".
2007 * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
2008 * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
2009 * If string, that format will be used for all of the values in $data.
2010 * A format is one of '%d', '%f', '%s' (integer, float, string).
2011 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
2012 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
2013 * If string, that format will be used for all of the items in $where.
2014 * A format is one of '%d', '%f', '%s' (integer, float, string).
2015 * If omitted, all values in $where will be treated as strings.
2016 * @return int|false The number of rows updated, or false on error.
2018 public function update( $table, $data, $where, $format = null, $where_format = null ) {
2019 if ( ! is_array( $data ) || ! is_array( $where ) ) {
2023 $data = $this->process_fields( $table, $data, $format );
2024 if ( false === $data ) {
2027 $where = $this->process_fields( $table, $where, $where_format );
2028 if ( false === $where ) {
2032 $fields = $conditions = $values = array();
2033 foreach ( $data as $field => $value ) {
2034 if ( is_null( $value['value'] ) ) {
2035 $fields[] = "`$field` = NULL";
2039 $fields[] = "`$field` = " . $value['format'];
2040 $values[] = $value['value'];
2042 foreach ( $where as $field => $value ) {
2043 if ( is_null( $value['value'] ) ) {
2044 $conditions[] = "`$field` IS NULL";
2048 $conditions[] = "`$field` = " . $value['format'];
2049 $values[] = $value['value'];
2052 $fields = implode( ', ', $fields );
2053 $conditions = implode( ' AND ', $conditions );
2055 $sql = "UPDATE `$table` SET $fields WHERE $conditions";
2057 $this->check_current_query = false;
2058 return $this->query( $this->prepare( $sql, $values ) );
2062 * Delete a row in the table
2064 * wpdb::delete( 'table', array( 'ID' => 1 ) )
2065 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
2068 * @see wpdb::prepare()
2069 * @see wpdb::$field_types
2070 * @see wp_set_wpdb_vars()
2072 * @param string $table Table name
2073 * @param array $where A named array of WHERE clauses (in column => value pairs).
2074 * Multiple clauses will be joined with ANDs.
2075 * Both $where columns and $where values should be "raw".
2076 * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
2077 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
2078 * If string, that format will be used for all of the items in $where.
2079 * A format is one of '%d', '%f', '%s' (integer, float, string).
2080 * If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
2081 * @return int|false The number of rows updated, or false on error.
2083 public function delete( $table, $where, $where_format = null ) {
2084 if ( ! is_array( $where ) ) {
2088 $where = $this->process_fields( $table, $where, $where_format );
2089 if ( false === $where ) {
2093 $conditions = $values = array();
2094 foreach ( $where as $field => $value ) {
2095 if ( is_null( $value['value'] ) ) {
2096 $conditions[] = "`$field` IS NULL";
2100 $conditions[] = "`$field` = " . $value['format'];
2101 $values[] = $value['value'];
2104 $conditions = implode( ' AND ', $conditions );
2106 $sql = "DELETE FROM `$table` WHERE $conditions";
2108 $this->check_current_query = false;
2109 return $this->query( $this->prepare( $sql, $values ) );
2113 * Processes arrays of field/value pairs and field formats.
2115 * This is a helper method for wpdb's CRUD methods, which take field/value
2116 * pairs for inserts, updates, and where clauses. This method first pairs
2117 * each value with a format. Then it determines the charset of that field,
2118 * using that to determine if any invalid text would be stripped. If text is
2119 * stripped, then field processing is rejected and the query fails.
2124 * @param string $table Table name.
2125 * @param array $data Field/value pair.
2126 * @param mixed $format Format for each field.
2127 * @return array|false Returns an array of fields that contain paired values
2128 * and formats. Returns false for invalid values.
2130 protected function process_fields( $table, $data, $format ) {
2131 $data = $this->process_field_formats( $data, $format );
2132 if ( false === $data ) {
2136 $data = $this->process_field_charsets( $data, $table );
2137 if ( false === $data ) {
2141 $data = $this->process_field_lengths( $data, $table );
2142 if ( false === $data ) {
2146 $converted_data = $this->strip_invalid_text( $data );
2148 if ( $data !== $converted_data ) {
2156 * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
2161 * @param array $data Array of fields to values.
2162 * @param mixed $format Formats to be mapped to the values in $data.
2163 * @return array Array, keyed by field names with values being an array
2164 * of 'value' and 'format' keys.
2166 protected function process_field_formats( $data, $format ) {
2167 $formats = $original_formats = (array) $format;
2169 foreach ( $data as $field => $value ) {
2175 if ( ! empty( $format ) ) {
2176 $value['format'] = array_shift( $formats );
2177 if ( ! $value['format'] ) {
2178 $value['format'] = reset( $original_formats );
2180 } elseif ( isset( $this->field_types[ $field ] ) ) {
2181 $value['format'] = $this->field_types[ $field ];
2184 $data[ $field ] = $value;
2191 * Adds field charsets to field/value/format arrays generated by
2192 * the wpdb::process_field_formats() method.
2197 * @param array $data As it comes from the wpdb::process_field_formats() method.
2198 * @param string $table Table name.
2199 * @return array|false The same array as $data with additional 'charset' keys.
2201 protected function process_field_charsets( $data, $table ) {
2202 foreach ( $data as $field => $value ) {
2203 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2205 * We can skip this field if we know it isn't a string.
2206 * This checks %d/%f versus ! %s because its sprintf() could take more.
2208 $value['charset'] = false;
2210 $value['charset'] = $this->get_col_charset( $table, $field );
2211 if ( is_wp_error( $value['charset'] ) ) {
2216 $data[ $field ] = $value;
2223 * For string fields, record the maximum string length that field can safely save.
2228 * @param array $data As it comes from the wpdb::process_field_charsets() method.
2229 * @param string $table Table name.
2230 * @return array|false The same array as $data with additional 'length' keys, or false if
2231 * any of the values were too long for their corresponding field.
2233 protected function process_field_lengths( $data, $table ) {
2234 foreach ( $data as $field => $value ) {
2235 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2237 * We can skip this field if we know it isn't a string.
2238 * This checks %d/%f versus ! %s because its sprintf() could take more.
2240 $value['length'] = false;
2242 $value['length'] = $this->get_col_length( $table, $field );
2243 if ( is_wp_error( $value['length'] ) ) {
2248 $data[ $field ] = $value;
2255 * Retrieve one variable from the database.
2257 * Executes a SQL query and returns the value from the SQL result.
2258 * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified.
2259 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2263 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2264 * @param int $x Optional. Column of value to return. Indexed from 0.
2265 * @param int $y Optional. Row of value to return. Indexed from 0.
2266 * @return string|null Database query result (as string), or null on failure
2268 public function get_var( $query = null, $x = 0, $y = 0 ) {
2269 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2271 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2272 $this->check_current_query = false;
2276 $this->query( $query );
2279 // Extract var out of cached results based x,y vals
2280 if ( !empty( $this->last_result[$y] ) ) {
2281 $values = array_values( get_object_vars( $this->last_result[$y] ) );
2284 // If there is a value return it else return null
2285 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2289 * Retrieve one row from the database.
2291 * Executes a SQL query and returns the row from the SQL result.
2295 * @param string|null $query SQL query.
2296 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants.
2297 * Return an associative array (column => value, ...),
2298 * a numerically indexed array (0 => value, ...) or
2299 * an object ( ->column = value ), respectively.
2300 * @param int $y Optional. Row to return. Indexed from 0.
2301 * @return array|object|null|void Database query result in format specified by $output or null on failure
2303 public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2304 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2306 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2307 $this->check_current_query = false;
2311 $this->query( $query );
2316 if ( !isset( $this->last_result[$y] ) )
2319 if ( $output == OBJECT ) {
2320 return $this->last_result[$y] ? $this->last_result[$y] : null;
2321 } elseif ( $output == ARRAY_A ) {
2322 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2323 } elseif ( $output == ARRAY_N ) {
2324 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2325 } elseif ( strtoupper( $output ) === OBJECT ) {
2326 // Back compat for OBJECT being previously case insensitive.
2327 return $this->last_result[$y] ? $this->last_result[$y] : null;
2329 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2334 * Retrieve one column from the database.
2336 * Executes a SQL query and returns the column from the SQL result.
2337 * If the SQL result contains more than one column, this function returns the column specified.
2338 * If $query is null, this function returns the specified column from the previous SQL result.
2342 * @param string|null $query Optional. SQL query. Defaults to previous query.
2343 * @param int $x Optional. Column to return. Indexed from 0.
2344 * @return array Database query result. Array indexed from 0 by SQL result row number.
2346 public function get_col( $query = null , $x = 0 ) {
2347 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2348 $this->check_current_query = false;
2352 $this->query( $query );
2355 $new_array = array();
2356 // Extract the column values
2357 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2358 $new_array[$i] = $this->get_var( null, $x, $i );
2364 * Retrieve an entire SQL result set from the database (i.e., many rows)
2366 * Executes a SQL query and returns the entire SQL result.
2370 * @param string $query SQL query.
2371 * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
2372 * With one of the first three, return an array of rows indexed from 0 by SQL result row number.
2373 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2374 * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.
2375 * Duplicate keys are discarded.
2376 * @return array|object|null Database query results
2378 public function get_results( $query = null, $output = OBJECT ) {
2379 $this->func_call = "\$db->get_results(\"$query\", $output)";
2381 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2382 $this->check_current_query = false;
2386 $this->query( $query );
2391 $new_array = array();
2392 if ( $output == OBJECT ) {
2393 // Return an integer-keyed array of row objects
2394 return $this->last_result;
2395 } elseif ( $output == OBJECT_K ) {
2396 // Return an array of row objects with keys from column 1
2397 // (Duplicates are discarded)
2398 foreach ( $this->last_result as $row ) {
2399 $var_by_ref = get_object_vars( $row );
2400 $key = array_shift( $var_by_ref );
2401 if ( ! isset( $new_array[ $key ] ) )
2402 $new_array[ $key ] = $row;
2405 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2406 // Return an integer-keyed array of...
2407 if ( $this->last_result ) {
2408 foreach ( (array) $this->last_result as $row ) {
2409 if ( $output == ARRAY_N ) {
2410 // ...integer-keyed row arrays
2411 $new_array[] = array_values( get_object_vars( $row ) );
2413 // ...column name-keyed row arrays
2414 $new_array[] = get_object_vars( $row );
2419 } elseif ( strtoupper( $output ) === OBJECT ) {
2420 // Back compat for OBJECT being previously case insensitive.
2421 return $this->last_result;
2427 * Retrieves the character set for the given table.
2432 * @param string $table Table name.
2433 * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
2435 protected function get_table_charset( $table ) {
2436 $tablekey = strtolower( $table );
2439 * Filters the table charset value before the DB is checked.
2441 * Passing a non-null value to the filter will effectively short-circuit
2442 * checking the DB for the charset, returning that value instead.
2446 * @param string $charset The character set to use. Default null.
2447 * @param string $table The name of the table being checked.
2449 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2450 if ( null !== $charset ) {
2454 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2455 return $this->table_charset[ $tablekey ];
2458 $charsets = $columns = array();
2460 $table_parts = explode( '.', $table );
2461 $table = '`' . implode( '`.`', $table_parts ) . '`';
2462 $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
2464 return new WP_Error( 'wpdb_get_table_charset_failure' );
2467 foreach ( $results as $column ) {
2468 $columns[ strtolower( $column->Field ) ] = $column;
2471 $this->col_meta[ $tablekey ] = $columns;
2473 foreach ( $columns as $column ) {
2474 if ( ! empty( $column->Collation ) ) {
2475 list( $charset ) = explode( '_', $column->Collation );
2477 // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
2478 if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
2482 $charsets[ strtolower( $charset ) ] = true;
2485 list( $type ) = explode( '(', $column->Type );
2487 // A binary/blob means the whole query gets treated like this.
2488 if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2489 $this->table_charset[ $tablekey ] = 'binary';
2494 // utf8mb3 is an alias for utf8.
2495 if ( isset( $charsets['utf8mb3'] ) ) {
2496 $charsets['utf8'] = true;
2497 unset( $charsets['utf8mb3'] );
2500 // Check if we have more than one charset in play.
2501 $count = count( $charsets );
2502 if ( 1 === $count ) {
2503 $charset = key( $charsets );
2504 } elseif ( 0 === $count ) {
2505 // No charsets, assume this table can store whatever.
2508 // More than one charset. Remove latin1 if present and recalculate.
2509 unset( $charsets['latin1'] );
2510 $count = count( $charsets );
2511 if ( 1 === $count ) {
2512 // Only one charset (besides latin1).
2513 $charset = key( $charsets );
2514 } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2515 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2518 // Two mixed character sets. ascii.
2523 $this->table_charset[ $tablekey ] = $charset;
2528 * Retrieves the character set for the given column.
2533 * @param string $table Table name.
2534 * @param string $column Column name.
2535 * @return string|false|WP_Error Column character set as a string. False if the column has no
2536 * character set. WP_Error object if there was an error.
2538 public function get_col_charset( $table, $column ) {
2539 $tablekey = strtolower( $table );
2540 $columnkey = strtolower( $column );
2543 * Filters the column charset value before the DB is checked.
2545 * Passing a non-null value to the filter will short-circuit
2546 * checking the DB for the charset, returning that value instead.
2550 * @param string $charset The character set to use. Default null.
2551 * @param string $table The name of the table being checked.
2552 * @param string $column The name of the column being checked.
2554 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2555 if ( null !== $charset ) {
2559 // Skip this entirely if this isn't a MySQL database.
2560 if ( empty( $this->is_mysql ) ) {
2564 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2565 // This primes column information for us.
2566 $table_charset = $this->get_table_charset( $table );
2567 if ( is_wp_error( $table_charset ) ) {
2568 return $table_charset;
2572 // If still no column information, return the table charset.
2573 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2574 return $this->table_charset[ $tablekey ];
2577 // If this column doesn't exist, return the table charset.
2578 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2579 return $this->table_charset[ $tablekey ];
2582 // Return false when it's not a string column.
2583 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2587 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2592 * Retrieve the maximum string length allowed in a given column.
2593 * The length may either be specified as a byte length or a character length.
2598 * @param string $table Table name.
2599 * @param string $column Column name.
2600 * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' )
2601 * false if the column has no length (for example, numeric column)
2602 * WP_Error object if there was an error.
2604 public function get_col_length( $table, $column ) {
2605 $tablekey = strtolower( $table );
2606 $columnkey = strtolower( $column );
2608 // Skip this entirely if this isn't a MySQL database.
2609 if ( empty( $this->is_mysql ) ) {
2613 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2614 // This primes column information for us.
2615 $table_charset = $this->get_table_charset( $table );
2616 if ( is_wp_error( $table_charset ) ) {
2617 return $table_charset;
2621 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2625 $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
2627 $type = strtolower( $typeinfo[0] );
2628 if ( ! empty( $typeinfo[1] ) ) {
2629 $length = trim( $typeinfo[1], ')' );
2639 'length' => (int) $length,
2646 'length' => (int) $length,
2653 'length' => 255, // 2^8 - 1
2660 'length' => 65535, // 2^16 - 1
2667 'length' => 16777215, // 2^24 - 1
2674 'length' => 4294967295, // 2^32 - 1
2683 * Check if a string is ASCII.
2685 * The negative regex is faster for non-ASCII strings, as it allows
2686 * the search to finish as soon as it encounters a non-ASCII character.
2691 * @param string $string String to check.
2692 * @return bool True if ASCII, false if not.
2694 protected function check_ascii( $string ) {
2695 if ( function_exists( 'mb_check_encoding' ) ) {
2696 if ( mb_check_encoding( $string, 'ASCII' ) ) {
2699 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2707 * Check if the query is accessing a collation considered safe on the current version of MySQL.
2712 * @param string $query The query to check.
2713 * @return bool True if the collation is safe, false if it isn't.
2715 protected function check_safe_collation( $query ) {
2716 if ( $this->checking_collation ) {
2720 // We don't need to check the collation for queries that don't read data.
2721 $query = ltrim( $query, "\r\n\t (" );
2722 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
2726 // All-ASCII queries don't need extra checking.
2727 if ( $this->check_ascii( $query ) ) {
2731 $table = $this->get_table_from_query( $query );
2736 $this->checking_collation = true;
2737 $collation = $this->get_table_charset( $table );
2738 $this->checking_collation = false;
2740 // Tables with no collation, or latin1 only, don't need extra checking.
2741 if ( false === $collation || 'latin1' === $collation ) {
2745 $table = strtolower( $table );
2746 if ( empty( $this->col_meta[ $table ] ) ) {
2750 // If any of the columns don't have one of these collations, it needs more sanity checking.
2751 foreach ( $this->col_meta[ $table ] as $col ) {
2752 if ( empty( $col->Collation ) ) {
2756 if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2765 * Strips any invalid characters based on value/charset pairs.
2770 * @param array $data Array of value arrays. Each value array has the keys
2771 * 'value' and 'charset'. An optional 'ascii' key can be
2772 * set to false to avoid redundant ASCII checks.
2773 * @return array|WP_Error The $data parameter, with invalid characters removed from
2774 * each value. This works as a passthrough: any additional keys
2775 * such as 'field' are retained in each value array. If we cannot
2776 * remove invalid characters, a WP_Error object is returned.
2778 protected function strip_invalid_text( $data ) {
2779 $db_check_string = false;
2781 foreach ( $data as &$value ) {
2782 $charset = $value['charset'];
2784 if ( is_array( $value['length'] ) ) {
2785 $length = $value['length']['length'];
2786 $truncate_by_byte_length = 'byte' === $value['length']['type'];
2789 // Since we have no length, we'll never truncate.
2790 // Initialize the variable to false. true would take us
2791 // through an unnecessary (for this case) codepath below.
2792 $truncate_by_byte_length = false;
2795 // There's no charset to work with.
2796 if ( false === $charset ) {
2800 // Column isn't a string.
2801 if ( ! is_string( $value['value'] ) ) {
2805 $needs_validation = true;
2807 // latin1 can store any byte sequence
2808 'latin1' === $charset
2810 // ASCII is always OK.
2811 ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
2813 $truncate_by_byte_length = true;
2814 $needs_validation = false;
2817 if ( $truncate_by_byte_length ) {
2818 mbstring_binary_safe_encoding();
2819 if ( false !== $length && strlen( $value['value'] ) > $length ) {
2820 $value['value'] = substr( $value['value'], 0, $length );
2822 reset_mbstring_encoding();
2824 if ( ! $needs_validation ) {
2829 // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2830 if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
2833 (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
2834 | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
2835 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
2836 | [\xE1-\xEC][\x80-\xBF]{2}
2837 | \xED[\x80-\x9F][\x80-\xBF]
2838 | [\xEE-\xEF][\x80-\xBF]{2}';
2840 if ( 'utf8mb4' === $charset ) {
2842 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
2843 | [\xF1-\xF3][\x80-\xBF]{3}
2844 | \xF4[\x80-\x8F][\x80-\xBF]{2}
2848 $regex .= '){1,40} # ...one or more times
2852 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2855 if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
2856 $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
2861 // We couldn't use any local conversions, send it to the DB.
2862 $value['db'] = $db_check_string = true;
2864 unset( $value ); // Remove by reference.
2866 if ( $db_check_string ) {
2868 foreach ( $data as $col => $value ) {
2869 if ( ! empty( $value['db'] ) ) {
2870 // We're going to need to truncate by characters or bytes, depending on the length value we have.
2871 if ( 'byte' === $value['length']['type'] ) {
2872 // Using binary causes LEFT() to truncate by bytes.
2873 $charset = 'binary';
2875 $charset = $value['charset'];
2878 if ( $this->charset ) {
2879 $connection_charset = $this->charset;
2881 if ( $this->use_mysqli ) {
2882 $connection_charset = mysqli_character_set_name( $this->dbh );
2884 $connection_charset = mysql_client_encoding();
2888 if ( is_array( $value['length'] ) ) {
2889 $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), %.0f ) USING $connection_charset )", $value['value'], $value['length']['length'] );
2890 } else if ( 'binary' !== $charset ) {
2891 // If we don't have a length, there's no need to convert binary - it will always return the same result.
2892 $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
2895 unset( $data[ $col ]['db'] );
2900 foreach ( $queries as $column => $query ) {
2905 $sql[] = $query . " AS x_$column";
2908 $this->check_current_query = false;
2909 $row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
2911 return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2914 foreach ( array_keys( $data ) as $column ) {
2915 if ( isset( $row["x_$column"] ) ) {
2916 $data[ $column ]['value'] = $row["x_$column"];
2925 * Strips any invalid characters from the query.
2930 * @param string $query Query to convert.
2931 * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
2933 protected function strip_invalid_text_from_query( $query ) {
2934 // We don't need to check the collation for queries that don't read data.
2935 $trimmed_query = ltrim( $query, "\r\n\t (" );
2936 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
2940 $table = $this->get_table_from_query( $query );
2942 $charset = $this->get_table_charset( $table );
2943 if ( is_wp_error( $charset ) ) {
2947 // We can't reliably strip text from tables containing binary/blob columns
2948 if ( 'binary' === $charset ) {
2952 $charset = $this->charset;
2957 'charset' => $charset,
2962 $data = $this->strip_invalid_text( array( $data ) );
2963 if ( is_wp_error( $data ) ) {
2967 return $data[0]['value'];
2971 * Strips any invalid characters from the string for a given table and column.
2976 * @param string $table Table name.
2977 * @param string $column Column name.
2978 * @param string $value The text to check.
2979 * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
2981 public function strip_invalid_text_for_column( $table, $column, $value ) {
2982 if ( ! is_string( $value ) ) {
2986 $charset = $this->get_col_charset( $table, $column );
2988 // Not a string column.
2990 } elseif ( is_wp_error( $charset ) ) {
2991 // Bail on real errors.
2998 'charset' => $charset,
2999 'length' => $this->get_col_length( $table, $column ),
3003 $data = $this->strip_invalid_text( $data );
3004 if ( is_wp_error( $data ) ) {
3008 return $data[ $column ]['value'];
3012 * Find the first table name referenced in a query.
3017 * @param string $query The query to search.
3018 * @return string|false $table The table name found, or false if a table couldn't be found.
3020 protected function get_table_from_query( $query ) {
3021 // Remove characters that can legally trail the table name.
3022 $query = rtrim( $query, ';/-#' );
3024 // Allow (select...) union [...] style queries. Use the first query's table name.
3025 $query = ltrim( $query, "\r\n\t (" );
3027 // Strip everything between parentheses except nested selects.
3028 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
3030 // Quickly match most common queries.
3031 if ( preg_match( '/^\s*(?:'
3032 . 'SELECT.*?\s+FROM'
3033 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
3034 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
3035 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
3036 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
3037 . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
3038 return str_replace( '`', '', $maybe[1] );
3041 // SHOW TABLE STATUS and SHOW TABLES
3042 if ( preg_match( '/^\s*(?:'
3043 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
3044 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
3045 . ')\W((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
3046 return str_replace( '`', '', $maybe[1] );
3049 // Big pattern for the rest of the table-related queries.
3050 if ( preg_match( '/^\s*(?:'
3051 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
3052 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
3053 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
3054 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
3055 . '|TRUNCATE(?:\s+TABLE)?'
3056 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
3057 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
3058 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
3059 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
3060 . '|DROP\s+INDEX.*\s+ON'
3061 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
3062 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
3063 . '|SHOW\s+(?:.*FROM|.*TABLE)'
3064 . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
3065 return str_replace( '`', '', $maybe[1] );
3072 * Load the column metadata from the last query.
3078 protected function load_col_info() {
3079 if ( $this->col_info )
3082 if ( $this->use_mysqli ) {
3083 $num_fields = mysqli_num_fields( $this->result );
3084 for ( $i = 0; $i < $num_fields; $i++ ) {
3085 $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
3088 $num_fields = mysql_num_fields( $this->result );
3089 for ( $i = 0; $i < $num_fields; $i++ ) {
3090 $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
3096 * Retrieve column metadata from the last query.
3100 * @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
3101 * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
3102 * @return mixed Column Results
3104 public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
3105 $this->load_col_info();
3107 if ( $this->col_info ) {
3108 if ( $col_offset == -1 ) {
3110 $new_array = array();
3111 foreach ( (array) $this->col_info as $col ) {
3112 $new_array[$i] = $col->{$info_type};
3117 return $this->col_info[$col_offset]->{$info_type};
3123 * Starts the timer, for debugging purposes.
3129 public function timer_start() {
3130 $this->time_start = microtime( true );
3135 * Stops the debugging timer.
3139 * @return float Total time spent on the query, in seconds
3141 public function timer_stop() {
3142 return ( microtime( true ) - $this->time_start );
3146 * Wraps errors in a nice header and footer and dies.
3148 * Will not die if wpdb::$show_errors is false.
3152 * @param string $message The Error message
3153 * @param string $error_code Optional. A Computer readable string to identify the error.
3154 * @return false|void
3156 public function bail( $message, $error_code = '500' ) {
3157 if ( !$this->show_errors ) {
3158 if ( class_exists( 'WP_Error', false ) ) {
3159 $this->error = new WP_Error($error_code, $message);
3161 $this->error = $message;
3170 * Closes the current database connection.
3175 * @return bool True if the connection was successfully closed, false if it wasn't,
3176 * or the connection doesn't exist.
3178 public function close() {
3179 if ( ! $this->dbh ) {
3183 if ( $this->use_mysqli ) {
3184 $closed = mysqli_close( $this->dbh );
3186 $closed = mysql_close( $this->dbh );
3191 $this->ready = false;
3192 $this->has_connected = false;
3199 * Whether MySQL database is at least the required minimum version.
3203 * @global string $wp_version
3204 * @global string $required_mysql_version
3206 * @return WP_Error|void
3208 public function check_database_version() {
3209 global $wp_version, $required_mysql_version;
3210 // Make sure the server has the required MySQL version
3211 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
3212 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
3216 * Whether the database supports collation.
3218 * Called when WordPress is generating the table scheme.
3220 * Use `wpdb::has_cap( 'collation' )`.
3223 * @deprecated 3.5.0 Use wpdb::has_cap()
3225 * @return bool True if collation is supported, false if version does not
3227 public function supports_collation() {
3228 _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
3229 return $this->has_cap( 'collation' );
3233 * The database character collate.
3237 * @return string The database character collate.
3239 public function get_charset_collate() {
3240 $charset_collate = '';
3242 if ( ! empty( $this->charset ) )
3243 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
3244 if ( ! empty( $this->collate ) )
3245 $charset_collate .= " COLLATE $this->collate";
3247 return $charset_collate;
3251 * Determine if a database supports a particular feature.
3254 * @since 4.1.0 Added support for the 'utf8mb4' feature.
3255 * @since 4.6.0 Added support for the 'utf8mb4_520' feature.
3257 * @see wpdb::db_version()
3259 * @param string $db_cap The feature to check for. Accepts 'collation',
3260 * 'group_concat', 'subqueries', 'set_charset',
3262 * @return int|false Whether the database feature is supported, false otherwise.
3264 public function has_cap( $db_cap ) {
3265 $version = $this->db_version();
3267 switch ( strtolower( $db_cap ) ) {
3268 case 'collation' : // @since 2.5.0
3269 case 'group_concat' : // @since 2.7.0
3270 case 'subqueries' : // @since 2.7.0
3271 return version_compare( $version, '4.1', '>=' );
3272 case 'set_charset' :
3273 return version_compare( $version, '5.0.7', '>=' );
3274 case 'utf8mb4' : // @since 4.1.0
3275 if ( version_compare( $version, '5.5.3', '<' ) ) {
3278 if ( $this->use_mysqli ) {
3279 $client_version = mysqli_get_client_info();
3281 $client_version = mysql_get_client_info();
3285 * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
3286 * mysqlnd has supported utf8mb4 since 5.0.9.
3288 if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
3289 $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
3290 return version_compare( $client_version, '5.0.9', '>=' );
3292 return version_compare( $client_version, '5.5.3', '>=' );
3294 case 'utf8mb4_520' : // @since 4.6.0
3295 return version_compare( $version, '5.6', '>=' );
3302 * Retrieve the name of the function that called wpdb.
3304 * Searches up the list of functions until it reaches
3305 * the one that would most logically had called this method.
3309 * @return string|array The name of the calling function
3311 public function get_caller() {
3312 return wp_debug_backtrace_summary( __CLASS__ );
3316 * Retrieves the MySQL server version.
3320 * @return null|string Null on failure, version number on success.
3322 public function db_version() {
3323 if ( $this->use_mysqli ) {
3324 $server_info = mysqli_get_server_info( $this->dbh );
3326 $server_info = mysql_get_server_info( $this->dbh );
3328 return preg_replace( '/[^0-9.].*/', '', $server_info );