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 * PHP5 style magic getter, used to lazy-load expensive data.
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 * Magic function, for backwards 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 * Magic function, for backwards 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 * Magic function, for backwards 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() {
737 if ( function_exists('is_multisite') && is_multisite() ) {
738 $this->charset = 'utf8';
739 if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
740 $this->collate = DB_COLLATE;
742 $this->collate = 'utf8_general_ci';
744 } elseif ( defined( 'DB_COLLATE' ) ) {
745 $this->collate = DB_COLLATE;
748 if ( defined( 'DB_CHARSET' ) ) {
749 $this->charset = DB_CHARSET;
752 if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
756 if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
757 $this->charset = 'utf8mb4';
760 if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
761 $this->collate = 'utf8mb4_unicode_ci';
766 * Sets the connection's character set.
770 * @param resource $dbh The resource given by mysql_connect
771 * @param string $charset Optional. The character set. Default null.
772 * @param string $collate Optional. The collation. Default null.
774 public function set_charset( $dbh, $charset = null, $collate = null ) {
775 if ( ! isset( $charset ) )
776 $charset = $this->charset;
777 if ( ! isset( $collate ) )
778 $collate = $this->collate;
779 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
780 if ( $this->use_mysqli ) {
781 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
782 mysqli_set_charset( $dbh, $charset );
784 $query = $this->prepare( 'SET NAMES %s', $charset );
785 if ( ! empty( $collate ) )
786 $query .= $this->prepare( ' COLLATE %s', $collate );
787 mysqli_query( $dbh, $query );
790 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
791 mysql_set_charset( $charset, $dbh );
793 $query = $this->prepare( 'SET NAMES %s', $charset );
794 if ( ! empty( $collate ) )
795 $query .= $this->prepare( ' COLLATE %s', $collate );
796 mysql_query( $query, $dbh );
803 * Change the current SQL mode, and ensure its WordPress compatibility.
805 * If no modes are passed, it will ensure the current MySQL server
806 * modes are compatible.
810 * @param array $modes Optional. A list of SQL modes to set.
812 public function set_sql_mode( $modes = array() ) {
813 if ( empty( $modes ) ) {
814 if ( $this->use_mysqli ) {
815 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
817 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
820 if ( empty( $res ) ) {
824 if ( $this->use_mysqli ) {
825 $modes_array = mysqli_fetch_array( $res );
826 if ( empty( $modes_array[0] ) ) {
829 $modes_str = $modes_array[0];
831 $modes_str = mysql_result( $res, 0 );
834 if ( empty( $modes_str ) ) {
838 $modes = explode( ',', $modes_str );
841 $modes = array_change_key_case( $modes, CASE_UPPER );
844 * Filter the list of incompatible SQL modes to exclude.
848 * @param array $incompatible_modes An array of incompatible modes.
850 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
852 foreach ( $modes as $i => $mode ) {
853 if ( in_array( $mode, $incompatible_modes ) ) {
854 unset( $modes[ $i ] );
858 $modes_str = implode( ',', $modes );
860 if ( $this->use_mysqli ) {
861 mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
863 mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
868 * Sets the table prefix for the WordPress tables.
872 * @param string $prefix Alphanumeric name for the new prefix.
873 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
874 * @return string|WP_Error Old prefix or WP_Error on error
876 public function set_prefix( $prefix, $set_table_names = true ) {
878 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
879 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
881 $old_prefix = is_multisite() ? '' : $prefix;
883 if ( isset( $this->base_prefix ) )
884 $old_prefix = $this->base_prefix;
886 $this->base_prefix = $prefix;
888 if ( $set_table_names ) {
889 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
890 $this->$table = $prefixed_table;
892 if ( is_multisite() && empty( $this->blogid ) )
895 $this->prefix = $this->get_blog_prefix();
897 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
898 $this->$table = $prefixed_table;
900 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
901 $this->$table = $prefixed_table;
912 * @param int $blog_id
913 * @param int $site_id Optional.
914 * @return int previous blog id
916 public function set_blog_id( $blog_id, $site_id = 0 ) {
917 if ( ! empty( $site_id ) )
918 $this->siteid = $site_id;
920 $old_blog_id = $this->blogid;
921 $this->blogid = $blog_id;
923 $this->prefix = $this->get_blog_prefix();
925 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
926 $this->$table = $prefixed_table;
928 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
929 $this->$table = $prefixed_table;
938 * @param int $blog_id Optional.
939 * @return string Blog prefix.
941 public function get_blog_prefix( $blog_id = null ) {
942 if ( is_multisite() ) {
943 if ( null === $blog_id )
944 $blog_id = $this->blogid;
945 $blog_id = (int) $blog_id;
946 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
947 return $this->base_prefix;
949 return $this->base_prefix . $blog_id . '_';
951 return $this->base_prefix;
956 * Returns an array of WordPress tables.
958 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
959 * override the WordPress users and usermeta tables that would otherwise
960 * be determined by the prefix.
962 * The scope argument can take one of the following:
964 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
965 * 'blog' - returns the blog-level tables for the queried blog.
966 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
967 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
968 * 'old' - returns tables which are deprecated.
971 * @uses wpdb::$tables
972 * @uses wpdb::$old_tables
973 * @uses wpdb::$global_tables
974 * @uses wpdb::$ms_global_tables
976 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
977 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
978 * prefix is requested, then the custom users and usermeta tables will be mapped.
979 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
980 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
982 public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
985 $tables = array_merge( $this->global_tables, $this->tables );
986 if ( is_multisite() )
987 $tables = array_merge( $tables, $this->ms_global_tables );
990 $tables = $this->tables;
993 $tables = $this->global_tables;
994 if ( is_multisite() )
995 $tables = array_merge( $tables, $this->ms_global_tables );
998 $tables = $this->ms_global_tables;
1001 $tables = $this->old_tables;
1009 $blog_id = $this->blogid;
1010 $blog_prefix = $this->get_blog_prefix( $blog_id );
1011 $base_prefix = $this->base_prefix;
1012 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
1013 foreach ( $tables as $k => $table ) {
1014 if ( in_array( $table, $global_tables ) )
1015 $tables[ $table ] = $base_prefix . $table;
1017 $tables[ $table ] = $blog_prefix . $table;
1018 unset( $tables[ $k ] );
1021 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
1022 $tables['users'] = CUSTOM_USER_TABLE;
1024 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
1025 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
1032 * Selects a database using the current database connection.
1034 * The database name will be changed based on the current database
1035 * connection. On failure, the execution will bail and display an DB error.
1039 * @param string $db MySQL database name
1040 * @param resource|null $dbh Optional link identifier.
1042 public function select( $db, $dbh = null ) {
1043 if ( is_null($dbh) )
1046 if ( $this->use_mysqli ) {
1047 $success = mysqli_select_db( $dbh, $db );
1049 $success = mysql_select_db( $db, $dbh );
1052 $this->ready = false;
1053 if ( ! did_action( 'template_redirect' ) ) {
1054 wp_load_translations_early();
1056 $message = '<h1>' . __( 'Can’t select database' ) . "</h1>\n";
1058 $message .= '<p>' . sprintf(
1059 /* translators: %s: database name */
1060 __( '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.' ),
1061 '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1064 $message .= "<ul>\n";
1065 $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
1067 $message .= '<li>' . sprintf(
1068 /* translators: 1: database user, 2: database name */
1069 __( 'Does the user %1$s have permission to use the %2$s database?' ),
1070 '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
1071 '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1074 $message .= '<li>' . sprintf(
1075 /* translators: %s: database name */
1076 __( '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?' ),
1077 htmlspecialchars( $db, ENT_QUOTES )
1080 $message .= "</ul>\n";
1082 $message .= '<p>' . sprintf(
1083 /* translators: %s: support forums URL */
1084 __( '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>.' ),
1085 __( 'https://wordpress.org/support/' )
1088 $this->bail( $message, 'db_select_fail' );
1094 * Do not use, deprecated.
1096 * Use esc_sql() or wpdb::prepare() instead.
1099 * @deprecated 3.6.0 Use wpdb::prepare()
1100 * @see wpdb::prepare
1104 * @param string $string
1107 function _weak_escape( $string ) {
1108 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1109 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1110 return addslashes( $string );
1114 * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1116 * @see mysqli_real_escape_string()
1117 * @see mysql_real_escape_string()
1121 * @param string $string to escape
1122 * @return string escaped
1124 function _real_escape( $string ) {
1126 if ( $this->use_mysqli ) {
1127 return mysqli_real_escape_string( $this->dbh, $string );
1129 return mysql_real_escape_string( $string, $this->dbh );
1133 $class = get_class( $this );
1134 if ( function_exists( '__' ) ) {
1135 /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
1136 _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
1138 _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
1140 return addslashes( $string );
1144 * Escape data. Works on arrays.
1146 * @uses wpdb::_real_escape()
1150 * @param string|array $data
1151 * @return string|array escaped
1153 function _escape( $data ) {
1154 if ( is_array( $data ) ) {
1155 foreach ( $data as $k => $v ) {
1157 $data[$k] = $this->_escape( $v );
1159 $data[$k] = $this->_real_escape( $v );
1162 $data = $this->_real_escape( $data );
1169 * Do not use, deprecated.
1171 * Use esc_sql() or wpdb::prepare() instead.
1174 * @deprecated 3.6.0 Use wpdb::prepare()
1175 * @see wpdb::prepare()
1178 * @param mixed $data
1181 public function escape( $data ) {
1182 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1183 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1184 if ( is_array( $data ) ) {
1185 foreach ( $data as $k => $v ) {
1186 if ( is_array( $v ) )
1187 $data[$k] = $this->escape( $v, 'recursive' );
1189 $data[$k] = $this->_weak_escape( $v, 'internal' );
1192 $data = $this->_weak_escape( $data, 'internal' );
1199 * Escapes content by reference for insertion into the database, for security
1201 * @uses wpdb::_real_escape()
1205 * @param string $string to escape
1207 public function escape_by_ref( &$string ) {
1208 if ( ! is_float( $string ) )
1209 $string = $this->_real_escape( $string );
1213 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1215 * The following directives can be used in the query format string:
1219 * %% (literal percentage sign - no argument needed)
1221 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1222 * Literals (%) as parts of the query must be properly written as %%.
1224 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1225 * Does not support sign, padding, alignment, width or precision specifiers.
1226 * Does not support argument numbering/swapping.
1228 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
1230 * Both %d and %s should be left unquoted in the query string.
1232 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1233 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1235 * @link http://php.net/sprintf Description of syntax.
1238 * @param string $query Query statement with sprintf()-like placeholders
1239 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1240 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1241 * being called like {@link http://php.net/sprintf sprintf()}.
1242 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1243 * {@link http://php.net/sprintf sprintf()}.
1244 * @return string|void Sanitized query string, if there is a query to prepare.
1246 public function prepare( $query, $args ) {
1247 if ( is_null( $query ) )
1250 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1251 if ( strpos( $query, '%' ) === false ) {
1252 _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
1255 $args = func_get_args();
1256 array_shift( $args );
1257 // If args were passed as an array (as in vsprintf), move them up
1258 if ( isset( $args[0] ) && is_array($args[0]) )
1260 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1261 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1262 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1263 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1264 array_walk( $args, array( $this, 'escape_by_ref' ) );
1265 return @vsprintf( $query, $args );
1269 * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1271 * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1273 * Example Prepared Statement:
1276 * $find = 'only 43% of planets';
1277 * $like = $wild . $wpdb->esc_like( $find ) . $wild;
1278 * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE '%s'", $like );
1280 * Example Escape Chain:
1282 * $sql = esc_sql( $wpdb->esc_like( $input ) );
1287 * @param string $text The raw text to be escaped. The input typed by the user should have no
1288 * extra or deleted slashes.
1289 * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1290 * or real_escape next.
1292 public function esc_like( $text ) {
1293 return addcslashes( $text, '_%\\' );
1297 * Print SQL/DB error.
1300 * @global array $EZSQL_ERROR Stores error information of query and error string
1302 * @param string $str The error to display
1303 * @return false|void False if the showing of errors is disabled.
1305 public function print_error( $str = '' ) {
1306 global $EZSQL_ERROR;
1309 if ( $this->use_mysqli ) {
1310 $str = mysqli_error( $this->dbh );
1312 $str = mysql_error( $this->dbh );
1315 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1317 if ( $this->suppress_errors )
1320 wp_load_translations_early();
1322 if ( $caller = $this->get_caller() )
1323 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1325 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1327 error_log( $error_str );
1329 // Are we showing errors?
1330 if ( ! $this->show_errors )
1333 // If there is an error then take note of it
1334 if ( is_multisite() ) {
1337 __( 'WordPress database error:' ),
1342 if ( defined( 'ERRORLOGFILE' ) ) {
1343 error_log( $msg, 3, ERRORLOGFILE );
1345 if ( defined( 'DIEONDBERROR' ) ) {
1349 $str = htmlspecialchars( $str, ENT_QUOTES );
1350 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1353 '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
1354 __( 'WordPress database error:' ),
1362 * Enables showing of database errors.
1364 * This function should be used only to enable showing of errors.
1365 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1366 * this function can be used to enable and disable showing of database
1370 * @see wpdb::hide_errors()
1372 * @param bool $show Whether to show or hide errors
1373 * @return bool Old value for showing errors.
1375 public function show_errors( $show = true ) {
1376 $errors = $this->show_errors;
1377 $this->show_errors = $show;
1382 * Disables showing of database errors.
1384 * By default database errors are not shown.
1387 * @see wpdb::show_errors()
1389 * @return bool Whether showing of errors was active
1391 public function hide_errors() {
1392 $show = $this->show_errors;
1393 $this->show_errors = false;
1398 * Whether to suppress database errors.
1400 * By default database errors are suppressed, with a simple
1401 * call to this function they can be enabled.
1404 * @see wpdb::hide_errors()
1405 * @param bool $suppress Optional. New value. Defaults to true.
1406 * @return bool Old value
1408 public function suppress_errors( $suppress = true ) {
1409 $errors = $this->suppress_errors;
1410 $this->suppress_errors = (bool) $suppress;
1415 * Kill cached query results.
1419 public function flush() {
1420 $this->last_result = array();
1421 $this->col_info = null;
1422 $this->last_query = null;
1423 $this->rows_affected = $this->num_rows = 0;
1424 $this->last_error = '';
1426 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1427 mysqli_free_result( $this->result );
1428 $this->result = null;
1430 // Sanity check before using the handle
1431 if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1435 // Clear out any results from a multi-query
1436 while ( mysqli_more_results( $this->dbh ) ) {
1437 mysqli_next_result( $this->dbh );
1439 } elseif ( is_resource( $this->result ) ) {
1440 mysql_free_result( $this->result );
1445 * Connect to and select database.
1447 * If $allow_bail is false, the lack of database connection will need
1448 * to be handled manually.
1451 * @since 3.9.0 $allow_bail parameter added.
1453 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1454 * @return bool True with a successful connection, false on failure.
1456 public function db_connect( $allow_bail = true ) {
1457 $this->is_mysql = true;
1460 * Deprecated in 3.9+ when using MySQLi. No equivalent
1461 * $new_link parameter exists for mysqli_* functions.
1463 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1464 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1466 if ( $this->use_mysqli ) {
1467 $this->dbh = mysqli_init();
1469 // mysqli_real_connect doesn't support the host param including a port or socket
1470 // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1473 $host = $this->dbhost;
1474 $port_or_socket = strstr( $host, ':' );
1475 if ( ! empty( $port_or_socket ) ) {
1476 $host = substr( $host, 0, strpos( $host, ':' ) );
1477 $port_or_socket = substr( $port_or_socket, 1 );
1478 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1479 $port = intval( $port_or_socket );
1480 $maybe_socket = strstr( $port_or_socket, ':' );
1481 if ( ! empty( $maybe_socket ) ) {
1482 $socket = substr( $maybe_socket, 1 );
1485 $socket = $port_or_socket;
1490 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1492 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1495 if ( $this->dbh->connect_errno ) {
1498 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1499 * - We haven't previously connected, and
1500 * - WP_USE_EXT_MYSQL isn't set to false, and
1501 * - ext/mysql is loaded.
1503 $attempt_fallback = true;
1505 if ( $this->has_connected ) {
1506 $attempt_fallback = false;
1507 } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1508 $attempt_fallback = false;
1509 } elseif ( ! function_exists( 'mysql_connect' ) ) {
1510 $attempt_fallback = false;
1513 if ( $attempt_fallback ) {
1514 $this->use_mysqli = false;
1515 return $this->db_connect( $allow_bail );
1520 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1522 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1526 if ( ! $this->dbh && $allow_bail ) {
1527 wp_load_translations_early();
1529 // Load custom DB error template, if present.
1530 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1531 require_once( WP_CONTENT_DIR . '/db-error.php' );
1535 $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
1537 $message .= '<p>' . sprintf(
1538 /* translators: 1: wp-config.php. 2: database host */
1539 __( '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.' ),
1540 '<code>wp-config.php</code>',
1541 '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1544 $message .= "<ul>\n";
1545 $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
1546 $message .= '<li>' . __( 'Are you sure that you have typed the correct hostname?' ) . "</li>\n";
1547 $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1548 $message .= "</ul>\n";
1550 $message .= '<p>' . sprintf(
1551 /* translators: %s: support forums URL */
1552 __( '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>.' ),
1553 __( 'https://wordpress.org/support/' )
1556 $this->bail( $message, 'db_connect_fail' );
1559 } elseif ( $this->dbh ) {
1560 if ( ! $this->has_connected ) {
1561 $this->init_charset();
1564 $this->has_connected = true;
1566 $this->set_charset( $this->dbh );
1568 $this->ready = true;
1569 $this->set_sql_mode();
1570 $this->select( $this->dbname, $this->dbh );
1579 * Check that the connection to the database is still up. If not, try to reconnect.
1581 * If this function is unable to reconnect, it will forcibly die, or if after the
1582 * the template_redirect hook has been fired, return false instead.
1584 * If $allow_bail is false, the lack of database connection will need
1585 * to be handled manually.
1589 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1590 * @return bool|void True if the connection is up.
1592 public function check_connection( $allow_bail = true ) {
1593 if ( $this->use_mysqli ) {
1594 if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
1598 if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
1603 $error_reporting = false;
1605 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1607 $error_reporting = error_reporting();
1608 error_reporting( $error_reporting & ~E_WARNING );
1611 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1612 // On the last try, re-enable warnings. We want to see a single instance of the
1613 // "unable to connect" message on the bail() screen, if it appears.
1614 if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1615 error_reporting( $error_reporting );
1618 if ( $this->db_connect( false ) ) {
1619 if ( $error_reporting ) {
1620 error_reporting( $error_reporting );
1629 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1630 // Let's just return and hope for the best.
1631 if ( did_action( 'template_redirect' ) ) {
1635 if ( ! $allow_bail ) {
1639 wp_load_translations_early();
1641 $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
1643 $message .= '<p>' . sprintf(
1644 /* translators: %s: database host */
1645 __( 'This means that we lost contact with the database server at %s. This could mean your host’s database server is down.' ),
1646 '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1649 $message .= "<ul>\n";
1650 $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1651 $message .= '<li>' . __( 'Are you sure that the database server is not under particularly heavy load?' ) . "</li>\n";
1652 $message .= "</ul>\n";
1654 $message .= '<p>' . sprintf(
1655 /* translators: %s: support forums URL */
1656 __( '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>.' ),
1657 __( 'https://wordpress.org/support/' )
1660 // We weren't able to reconnect, so we better bail.
1661 $this->bail( $message, 'db_connect_fail' );
1663 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1668 * Perform a MySQL database query, using current database connection.
1670 * More information can be found on the codex page.
1674 * @param string $query Database query
1675 * @return int|false Number of rows affected/selected or false on error
1677 public function query( $query ) {
1678 if ( ! $this->ready ) {
1679 $this->check_current_query = true;
1684 * Filter the database query.
1686 * Some queries are made before the plugins have been loaded,
1687 * and thus cannot be filtered with this method.
1691 * @param string $query Database query.
1693 $query = apply_filters( 'query', $query );
1697 // Log how the function was called
1698 $this->func_call = "\$db->query(\"$query\")";
1700 // If we're writing to the database, make sure the query will write safely.
1701 if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
1702 $stripped_query = $this->strip_invalid_text_from_query( $query );
1703 // strip_invalid_text_from_query() can perform queries, so we need
1704 // to flush again, just to make sure everything is clear.
1706 if ( $stripped_query !== $query ) {
1707 $this->insert_id = 0;
1712 $this->check_current_query = true;
1714 // Keep track of the last query for debug..
1715 $this->last_query = $query;
1717 $this->_do_query( $query );
1719 // MySQL server has gone away, try to reconnect
1721 if ( ! empty( $this->dbh ) ) {
1722 if ( $this->use_mysqli ) {
1723 $mysql_errno = mysqli_errno( $this->dbh );
1725 $mysql_errno = mysql_errno( $this->dbh );
1729 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1730 if ( $this->check_connection() ) {
1731 $this->_do_query( $query );
1733 $this->insert_id = 0;
1738 // If there is an error then take note of it..
1739 if ( $this->use_mysqli ) {
1740 $this->last_error = mysqli_error( $this->dbh );
1742 $this->last_error = mysql_error( $this->dbh );
1745 if ( $this->last_error ) {
1746 // Clear insert_id on a subsequent failed insert.
1747 if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1748 $this->insert_id = 0;
1750 $this->print_error();
1754 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1755 $return_val = $this->result;
1756 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1757 if ( $this->use_mysqli ) {
1758 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1760 $this->rows_affected = mysql_affected_rows( $this->dbh );
1762 // Take note of the insert_id
1763 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1764 if ( $this->use_mysqli ) {
1765 $this->insert_id = mysqli_insert_id( $this->dbh );
1767 $this->insert_id = mysql_insert_id( $this->dbh );
1770 // Return number of rows affected
1771 $return_val = $this->rows_affected;
1774 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1775 while ( $row = mysqli_fetch_object( $this->result ) ) {
1776 $this->last_result[$num_rows] = $row;
1779 } elseif ( is_resource( $this->result ) ) {
1780 while ( $row = mysql_fetch_object( $this->result ) ) {
1781 $this->last_result[$num_rows] = $row;
1786 // Log number of rows the query returned
1787 // and return number of rows selected
1788 $this->num_rows = $num_rows;
1789 $return_val = $num_rows;
1796 * Internal function to perform the mysql_query() call.
1801 * @see wpdb::query()
1803 * @param string $query The query to run.
1805 private function _do_query( $query ) {
1806 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1807 $this->timer_start();
1810 if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
1811 $this->result = mysqli_query( $this->dbh, $query );
1812 } elseif ( ! empty( $this->dbh ) ) {
1813 $this->result = mysql_query( $query, $this->dbh );
1815 $this->num_queries++;
1817 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1818 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1823 * Insert a row into a table.
1825 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1826 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1829 * @see wpdb::prepare()
1830 * @see wpdb::$field_types
1831 * @see wp_set_wpdb_vars()
1833 * @param string $table Table name
1834 * @param array $data Data to insert (in column => value pairs).
1835 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1836 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1837 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1838 * If string, that format will be used for all of the values in $data.
1839 * A format is one of '%d', '%f', '%s' (integer, float, string).
1840 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1841 * @return int|false The number of rows inserted, or false on error.
1843 public function insert( $table, $data, $format = null ) {
1844 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1848 * Replace a row into a table.
1850 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1851 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1854 * @see wpdb::prepare()
1855 * @see wpdb::$field_types
1856 * @see wp_set_wpdb_vars()
1858 * @param string $table Table name
1859 * @param array $data Data to insert (in column => value pairs).
1860 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1861 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1862 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1863 * If string, that format will be used for all of the values in $data.
1864 * A format is one of '%d', '%f', '%s' (integer, float, string).
1865 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1866 * @return int|false The number of rows affected, or false on error.
1868 public function replace( $table, $data, $format = null ) {
1869 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1873 * Helper function for insert and replace.
1875 * Runs an insert or replace query based on $type argument.
1879 * @see wpdb::prepare()
1880 * @see wpdb::$field_types
1881 * @see wp_set_wpdb_vars()
1883 * @param string $table Table name
1884 * @param array $data Data to insert (in column => value pairs).
1885 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1886 * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1887 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1888 * If string, that format will be used for all of the values in $data.
1889 * A format is one of '%d', '%f', '%s' (integer, float, string).
1890 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1891 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1892 * @return int|false The number of rows affected, or false on error.
1894 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1895 $this->insert_id = 0;
1897 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
1901 $data = $this->process_fields( $table, $data, $format );
1902 if ( false === $data ) {
1906 $formats = $values = array();
1907 foreach ( $data as $value ) {
1908 if ( is_null( $value['value'] ) ) {
1909 $formats[] = 'NULL';
1913 $formats[] = $value['format'];
1914 $values[] = $value['value'];
1917 $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
1918 $formats = implode( ', ', $formats );
1920 $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
1922 $this->check_current_query = false;
1923 return $this->query( $this->prepare( $sql, $values ) );
1927 * Update a row in the table
1929 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1930 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1933 * @see wpdb::prepare()
1934 * @see wpdb::$field_types
1935 * @see wp_set_wpdb_vars()
1937 * @param string $table Table name
1938 * @param array $data Data to update (in column => value pairs).
1939 * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1940 * Sending a null value will cause the column to be set to NULL - the corresponding
1941 * format is ignored in this case.
1942 * @param array $where A named array of WHERE clauses (in column => value pairs).
1943 * Multiple clauses will be joined with ANDs.
1944 * Both $where columns and $where values should be "raw".
1945 * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
1946 * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
1947 * If string, that format will be used for all of the values in $data.
1948 * A format is one of '%d', '%f', '%s' (integer, float, string).
1949 * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1950 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
1951 * If string, that format will be used for all of the items in $where.
1952 * A format is one of '%d', '%f', '%s' (integer, float, string).
1953 * If omitted, all values in $where will be treated as strings.
1954 * @return int|false The number of rows updated, or false on error.
1956 public function update( $table, $data, $where, $format = null, $where_format = null ) {
1957 if ( ! is_array( $data ) || ! is_array( $where ) ) {
1961 $data = $this->process_fields( $table, $data, $format );
1962 if ( false === $data ) {
1965 $where = $this->process_fields( $table, $where, $where_format );
1966 if ( false === $where ) {
1970 $fields = $conditions = $values = array();
1971 foreach ( $data as $field => $value ) {
1972 if ( is_null( $value['value'] ) ) {
1973 $fields[] = "`$field` = NULL";
1977 $fields[] = "`$field` = " . $value['format'];
1978 $values[] = $value['value'];
1980 foreach ( $where as $field => $value ) {
1981 if ( is_null( $value['value'] ) ) {
1982 $conditions[] = "`$field` IS NULL";
1986 $conditions[] = "`$field` = " . $value['format'];
1987 $values[] = $value['value'];
1990 $fields = implode( ', ', $fields );
1991 $conditions = implode( ' AND ', $conditions );
1993 $sql = "UPDATE `$table` SET $fields WHERE $conditions";
1995 $this->check_current_query = false;
1996 return $this->query( $this->prepare( $sql, $values ) );
2000 * Delete a row in the table
2002 * wpdb::delete( 'table', array( 'ID' => 1 ) )
2003 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
2006 * @see wpdb::prepare()
2007 * @see wpdb::$field_types
2008 * @see wp_set_wpdb_vars()
2010 * @param string $table Table name
2011 * @param array $where A named array of WHERE clauses (in column => value pairs).
2012 * Multiple clauses will be joined with ANDs.
2013 * Both $where columns and $where values should be "raw".
2014 * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
2015 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
2016 * If string, that format will be used for all of the items in $where.
2017 * A format is one of '%d', '%f', '%s' (integer, float, string).
2018 * If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
2019 * @return int|false The number of rows updated, or false on error.
2021 public function delete( $table, $where, $where_format = null ) {
2022 if ( ! is_array( $where ) ) {
2026 $where = $this->process_fields( $table, $where, $where_format );
2027 if ( false === $where ) {
2031 $conditions = $values = array();
2032 foreach ( $where as $field => $value ) {
2033 if ( is_null( $value['value'] ) ) {
2034 $conditions[] = "`$field` IS NULL";
2038 $conditions[] = "`$field` = " . $value['format'];
2039 $values[] = $value['value'];
2042 $conditions = implode( ' AND ', $conditions );
2044 $sql = "DELETE FROM `$table` WHERE $conditions";
2046 $this->check_current_query = false;
2047 return $this->query( $this->prepare( $sql, $values ) );
2051 * Processes arrays of field/value pairs and field formats.
2053 * This is a helper method for wpdb's CRUD methods, which take field/value
2054 * pairs for inserts, updates, and where clauses. This method first pairs
2055 * each value with a format. Then it determines the charset of that field,
2056 * using that to determine if any invalid text would be stripped. If text is
2057 * stripped, then field processing is rejected and the query fails.
2062 * @param string $table Table name.
2063 * @param array $data Field/value pair.
2064 * @param mixed $format Format for each field.
2065 * @return array|false Returns an array of fields that contain paired values
2066 * and formats. Returns false for invalid values.
2068 protected function process_fields( $table, $data, $format ) {
2069 $data = $this->process_field_formats( $data, $format );
2070 if ( false === $data ) {
2074 $data = $this->process_field_charsets( $data, $table );
2075 if ( false === $data ) {
2079 $data = $this->process_field_lengths( $data, $table );
2080 if ( false === $data ) {
2084 $converted_data = $this->strip_invalid_text( $data );
2086 if ( $data !== $converted_data ) {
2094 * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
2099 * @param array $data Array of fields to values.
2100 * @param mixed $format Formats to be mapped to the values in $data.
2101 * @return array Array, keyed by field names with values being an array
2102 * of 'value' and 'format' keys.
2104 protected function process_field_formats( $data, $format ) {
2105 $formats = $original_formats = (array) $format;
2107 foreach ( $data as $field => $value ) {
2113 if ( ! empty( $format ) ) {
2114 $value['format'] = array_shift( $formats );
2115 if ( ! $value['format'] ) {
2116 $value['format'] = reset( $original_formats );
2118 } elseif ( isset( $this->field_types[ $field ] ) ) {
2119 $value['format'] = $this->field_types[ $field ];
2122 $data[ $field ] = $value;
2129 * Adds field charsets to field/value/format arrays generated by
2130 * the wpdb::process_field_formats() method.
2135 * @param array $data As it comes from the wpdb::process_field_formats() method.
2136 * @param string $table Table name.
2137 * @return array|false The same array as $data with additional 'charset' keys.
2139 protected function process_field_charsets( $data, $table ) {
2140 foreach ( $data as $field => $value ) {
2141 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2143 * We can skip this field if we know it isn't a string.
2144 * This checks %d/%f versus ! %s because its sprintf() could take more.
2146 $value['charset'] = false;
2148 $value['charset'] = $this->get_col_charset( $table, $field );
2149 if ( is_wp_error( $value['charset'] ) ) {
2154 $data[ $field ] = $value;
2161 * For string fields, record the maximum string length that field can safely save.
2166 * @param array $data As it comes from the wpdb::process_field_charsets() method.
2167 * @param string $table Table name.
2168 * @return array|false The same array as $data with additional 'length' keys, or false if
2169 * any of the values were too long for their corresponding field.
2171 protected function process_field_lengths( $data, $table ) {
2172 foreach ( $data as $field => $value ) {
2173 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2175 * We can skip this field if we know it isn't a string.
2176 * This checks %d/%f versus ! %s because its sprintf() could take more.
2178 $value['length'] = false;
2180 $value['length'] = $this->get_col_length( $table, $field );
2181 if ( is_wp_error( $value['length'] ) ) {
2186 $data[ $field ] = $value;
2193 * Retrieve one variable from the database.
2195 * Executes a SQL query and returns the value from the SQL result.
2196 * 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.
2197 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2201 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2202 * @param int $x Optional. Column of value to return. Indexed from 0.
2203 * @param int $y Optional. Row of value to return. Indexed from 0.
2204 * @return string|null Database query result (as string), or null on failure
2206 public function get_var( $query = null, $x = 0, $y = 0 ) {
2207 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2209 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2210 $this->check_current_query = false;
2214 $this->query( $query );
2217 // Extract var out of cached results based x,y vals
2218 if ( !empty( $this->last_result[$y] ) ) {
2219 $values = array_values( get_object_vars( $this->last_result[$y] ) );
2222 // If there is a value return it else return null
2223 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2227 * Retrieve one row from the database.
2229 * Executes a SQL query and returns the row from the SQL result.
2233 * @param string|null $query SQL query.
2234 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants.
2235 * Return an associative array (column => value, ...),
2236 * a numerically indexed array (0 => value, ...) or
2237 * an object ( ->column = value ), respectively.
2238 * @param int $y Optional. Row to return. Indexed from 0.
2239 * @return array|object|null|void Database query result in format specified by $output or null on failure
2241 public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2242 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2244 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2245 $this->check_current_query = false;
2249 $this->query( $query );
2254 if ( !isset( $this->last_result[$y] ) )
2257 if ( $output == OBJECT ) {
2258 return $this->last_result[$y] ? $this->last_result[$y] : null;
2259 } elseif ( $output == ARRAY_A ) {
2260 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2261 } elseif ( $output == ARRAY_N ) {
2262 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2263 } elseif ( strtoupper( $output ) === OBJECT ) {
2264 // Back compat for OBJECT being previously case insensitive.
2265 return $this->last_result[$y] ? $this->last_result[$y] : null;
2267 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2272 * Retrieve one column from the database.
2274 * Executes a SQL query and returns the column from the SQL result.
2275 * If the SQL result contains more than one column, this function returns the column specified.
2276 * If $query is null, this function returns the specified column from the previous SQL result.
2280 * @param string|null $query Optional. SQL query. Defaults to previous query.
2281 * @param int $x Optional. Column to return. Indexed from 0.
2282 * @return array Database query result. Array indexed from 0 by SQL result row number.
2284 public function get_col( $query = null , $x = 0 ) {
2285 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2286 $this->check_current_query = false;
2290 $this->query( $query );
2293 $new_array = array();
2294 // Extract the column values
2295 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2296 $new_array[$i] = $this->get_var( null, $x, $i );
2302 * Retrieve an entire SQL result set from the database (i.e., many rows)
2304 * Executes a SQL query and returns the entire SQL result.
2308 * @param string $query SQL query.
2309 * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
2310 * With one of the first three, return an array of rows indexed from 0 by SQL result row number.
2311 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2312 * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.
2313 * Duplicate keys are discarded.
2314 * @return array|object|null Database query results
2316 public function get_results( $query = null, $output = OBJECT ) {
2317 $this->func_call = "\$db->get_results(\"$query\", $output)";
2319 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2320 $this->check_current_query = false;
2324 $this->query( $query );
2329 $new_array = array();
2330 if ( $output == OBJECT ) {
2331 // Return an integer-keyed array of row objects
2332 return $this->last_result;
2333 } elseif ( $output == OBJECT_K ) {
2334 // Return an array of row objects with keys from column 1
2335 // (Duplicates are discarded)
2336 foreach ( $this->last_result as $row ) {
2337 $var_by_ref = get_object_vars( $row );
2338 $key = array_shift( $var_by_ref );
2339 if ( ! isset( $new_array[ $key ] ) )
2340 $new_array[ $key ] = $row;
2343 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2344 // Return an integer-keyed array of...
2345 if ( $this->last_result ) {
2346 foreach ( (array) $this->last_result as $row ) {
2347 if ( $output == ARRAY_N ) {
2348 // ...integer-keyed row arrays
2349 $new_array[] = array_values( get_object_vars( $row ) );
2351 // ...column name-keyed row arrays
2352 $new_array[] = get_object_vars( $row );
2357 } elseif ( strtoupper( $output ) === OBJECT ) {
2358 // Back compat for OBJECT being previously case insensitive.
2359 return $this->last_result;
2365 * Retrieves the character set for the given table.
2370 * @param string $table Table name.
2371 * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
2373 protected function get_table_charset( $table ) {
2374 $tablekey = strtolower( $table );
2377 * Filter the table charset value before the DB is checked.
2379 * Passing a non-null value to the filter will effectively short-circuit
2380 * checking the DB for the charset, returning that value instead.
2384 * @param string $charset The character set to use. Default null.
2385 * @param string $table The name of the table being checked.
2387 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2388 if ( null !== $charset ) {
2392 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2393 return $this->table_charset[ $tablekey ];
2396 $charsets = $columns = array();
2398 $table_parts = explode( '.', $table );
2399 $table = '`' . implode( '`.`', $table_parts ) . '`';
2400 $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
2402 return new WP_Error( 'wpdb_get_table_charset_failure' );
2405 foreach ( $results as $column ) {
2406 $columns[ strtolower( $column->Field ) ] = $column;
2409 $this->col_meta[ $tablekey ] = $columns;
2411 foreach ( $columns as $column ) {
2412 if ( ! empty( $column->Collation ) ) {
2413 list( $charset ) = explode( '_', $column->Collation );
2415 // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
2416 if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
2420 $charsets[ strtolower( $charset ) ] = true;
2423 list( $type ) = explode( '(', $column->Type );
2425 // A binary/blob means the whole query gets treated like this.
2426 if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2427 $this->table_charset[ $tablekey ] = 'binary';
2432 // utf8mb3 is an alias for utf8.
2433 if ( isset( $charsets['utf8mb3'] ) ) {
2434 $charsets['utf8'] = true;
2435 unset( $charsets['utf8mb3'] );
2438 // Check if we have more than one charset in play.
2439 $count = count( $charsets );
2440 if ( 1 === $count ) {
2441 $charset = key( $charsets );
2442 } elseif ( 0 === $count ) {
2443 // No charsets, assume this table can store whatever.
2446 // More than one charset. Remove latin1 if present and recalculate.
2447 unset( $charsets['latin1'] );
2448 $count = count( $charsets );
2449 if ( 1 === $count ) {
2450 // Only one charset (besides latin1).
2451 $charset = key( $charsets );
2452 } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2453 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2456 // Two mixed character sets. ascii.
2461 $this->table_charset[ $tablekey ] = $charset;
2466 * Retrieves the character set for the given column.
2471 * @param string $table Table name.
2472 * @param string $column Column name.
2473 * @return string|false|WP_Error Column character set as a string. False if the column has no
2474 * character set. WP_Error object if there was an error.
2476 public function get_col_charset( $table, $column ) {
2477 $tablekey = strtolower( $table );
2478 $columnkey = strtolower( $column );
2481 * Filter the column charset value before the DB is checked.
2483 * Passing a non-null value to the filter will short-circuit
2484 * checking the DB for the charset, returning that value instead.
2488 * @param string $charset The character set to use. Default null.
2489 * @param string $table The name of the table being checked.
2490 * @param string $column The name of the column being checked.
2492 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2493 if ( null !== $charset ) {
2497 // Skip this entirely if this isn't a MySQL database.
2498 if ( empty( $this->is_mysql ) ) {
2502 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2503 // This primes column information for us.
2504 $table_charset = $this->get_table_charset( $table );
2505 if ( is_wp_error( $table_charset ) ) {
2506 return $table_charset;
2510 // If still no column information, return the table charset.
2511 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2512 return $this->table_charset[ $tablekey ];
2515 // If this column doesn't exist, return the table charset.
2516 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2517 return $this->table_charset[ $tablekey ];
2520 // Return false when it's not a string column.
2521 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2525 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2530 * Retrieve the maximum string length allowed in a given column.
2531 * The length may either be specified as a byte length or a character length.
2536 * @param string $table Table name.
2537 * @param string $column Column name.
2538 * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' )
2539 * false if the column has no length (for example, numeric column)
2540 * WP_Error object if there was an error.
2542 public function get_col_length( $table, $column ) {
2543 $tablekey = strtolower( $table );
2544 $columnkey = strtolower( $column );
2546 // Skip this entirely if this isn't a MySQL database.
2547 if ( empty( $this->is_mysql ) ) {
2551 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2552 // This primes column information for us.
2553 $table_charset = $this->get_table_charset( $table );
2554 if ( is_wp_error( $table_charset ) ) {
2555 return $table_charset;
2559 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2563 $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
2565 $type = strtolower( $typeinfo[0] );
2566 if ( ! empty( $typeinfo[1] ) ) {
2567 $length = trim( $typeinfo[1], ')' );
2577 'length' => (int) $length,
2584 'length' => (int) $length,
2591 'length' => 255, // 2^8 - 1
2598 'length' => 65535, // 2^16 - 1
2605 'length' => 16777215, // 2^24 - 1
2612 'length' => 4294967295, // 2^32 - 1
2621 * Check if a string is ASCII.
2623 * The negative regex is faster for non-ASCII strings, as it allows
2624 * the search to finish as soon as it encounters a non-ASCII character.
2629 * @param string $string String to check.
2630 * @return bool True if ASCII, false if not.
2632 protected function check_ascii( $string ) {
2633 if ( function_exists( 'mb_check_encoding' ) ) {
2634 if ( mb_check_encoding( $string, 'ASCII' ) ) {
2637 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2645 * Check if the query is accessing a collation considered safe on the current version of MySQL.
2650 * @param string $query The query to check.
2651 * @return bool True if the collation is safe, false if it isn't.
2653 protected function check_safe_collation( $query ) {
2654 if ( $this->checking_collation ) {
2658 // We don't need to check the collation for queries that don't read data.
2659 $query = ltrim( $query, "\r\n\t (" );
2660 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
2664 // All-ASCII queries don't need extra checking.
2665 if ( $this->check_ascii( $query ) ) {
2669 $table = $this->get_table_from_query( $query );
2674 $this->checking_collation = true;
2675 $collation = $this->get_table_charset( $table );
2676 $this->checking_collation = false;
2678 // Tables with no collation, or latin1 only, don't need extra checking.
2679 if ( false === $collation || 'latin1' === $collation ) {
2683 $table = strtolower( $table );
2684 if ( empty( $this->col_meta[ $table ] ) ) {
2688 // If any of the columns don't have one of these collations, it needs more sanity checking.
2689 foreach ( $this->col_meta[ $table ] as $col ) {
2690 if ( empty( $col->Collation ) ) {
2694 if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2703 * Strips any invalid characters based on value/charset pairs.
2708 * @param array $data Array of value arrays. Each value array has the keys
2709 * 'value' and 'charset'. An optional 'ascii' key can be
2710 * set to false to avoid redundant ASCII checks.
2711 * @return array|WP_Error The $data parameter, with invalid characters removed from
2712 * each value. This works as a passthrough: any additional keys
2713 * such as 'field' are retained in each value array. If we cannot
2714 * remove invalid characters, a WP_Error object is returned.
2716 protected function strip_invalid_text( $data ) {
2717 $db_check_string = false;
2719 foreach ( $data as &$value ) {
2720 $charset = $value['charset'];
2722 if ( is_array( $value['length'] ) ) {
2723 $length = $value['length']['length'];
2724 $truncate_by_byte_length = 'byte' === $value['length']['type'];
2727 // Since we have no length, we'll never truncate.
2728 // Initialize the variable to false. true would take us
2729 // through an unnecessary (for this case) codepath below.
2730 $truncate_by_byte_length = false;
2733 // There's no charset to work with.
2734 if ( false === $charset ) {
2738 // Column isn't a string.
2739 if ( ! is_string( $value['value'] ) ) {
2743 $needs_validation = true;
2745 // latin1 can store any byte sequence
2746 'latin1' === $charset
2748 // ASCII is always OK.
2749 ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
2751 $truncate_by_byte_length = true;
2752 $needs_validation = false;
2755 if ( $truncate_by_byte_length ) {
2756 mbstring_binary_safe_encoding();
2757 if ( false !== $length && strlen( $value['value'] ) > $length ) {
2758 $value['value'] = substr( $value['value'], 0, $length );
2760 reset_mbstring_encoding();
2762 if ( ! $needs_validation ) {
2767 // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2768 if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
2771 (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
2772 | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
2773 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
2774 | [\xE1-\xEC][\x80-\xBF]{2}
2775 | \xED[\x80-\x9F][\x80-\xBF]
2776 | [\xEE-\xEF][\x80-\xBF]{2}';
2778 if ( 'utf8mb4' === $charset ) {
2780 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
2781 | [\xF1-\xF3][\x80-\xBF]{3}
2782 | \xF4[\x80-\x8F][\x80-\xBF]{2}
2786 $regex .= '){1,40} # ...one or more times
2790 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2793 if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
2794 $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
2799 // We couldn't use any local conversions, send it to the DB.
2800 $value['db'] = $db_check_string = true;
2802 unset( $value ); // Remove by reference.
2804 if ( $db_check_string ) {
2806 foreach ( $data as $col => $value ) {
2807 if ( ! empty( $value['db'] ) ) {
2808 // We're going to need to truncate by characters or bytes, depending on the length value we have.
2809 if ( 'byte' === $value['length']['type'] ) {
2810 // Using binary causes LEFT() to truncate by bytes.
2811 $charset = 'binary';
2813 $charset = $value['charset'];
2816 if ( $this->charset ) {
2817 $connection_charset = $this->charset;
2819 if ( $this->use_mysqli ) {
2820 $connection_charset = mysqli_character_set_name( $this->dbh );
2822 $connection_charset = mysql_client_encoding();
2826 if ( is_array( $value['length'] ) ) {
2827 $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), %.0f ) USING $connection_charset )", $value['value'], $value['length']['length'] );
2828 } else if ( 'binary' !== $charset ) {
2829 // If we don't have a length, there's no need to convert binary - it will always return the same result.
2830 $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
2833 unset( $data[ $col ]['db'] );
2838 foreach ( $queries as $column => $query ) {
2843 $sql[] = $query . " AS x_$column";
2846 $this->check_current_query = false;
2847 $row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
2849 return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2852 foreach ( array_keys( $data ) as $column ) {
2853 if ( isset( $row["x_$column"] ) ) {
2854 $data[ $column ]['value'] = $row["x_$column"];
2863 * Strips any invalid characters from the query.
2868 * @param string $query Query to convert.
2869 * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
2871 protected function strip_invalid_text_from_query( $query ) {
2872 // We don't need to check the collation for queries that don't read data.
2873 $trimmed_query = ltrim( $query, "\r\n\t (" );
2874 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
2878 $table = $this->get_table_from_query( $query );
2880 $charset = $this->get_table_charset( $table );
2881 if ( is_wp_error( $charset ) ) {
2885 // We can't reliably strip text from tables containing binary/blob columns
2886 if ( 'binary' === $charset ) {
2890 $charset = $this->charset;
2895 'charset' => $charset,
2900 $data = $this->strip_invalid_text( array( $data ) );
2901 if ( is_wp_error( $data ) ) {
2905 return $data[0]['value'];
2909 * Strips any invalid characters from the string for a given table and column.
2914 * @param string $table Table name.
2915 * @param string $column Column name.
2916 * @param string $value The text to check.
2917 * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
2919 public function strip_invalid_text_for_column( $table, $column, $value ) {
2920 if ( ! is_string( $value ) ) {
2924 $charset = $this->get_col_charset( $table, $column );
2926 // Not a string column.
2928 } elseif ( is_wp_error( $charset ) ) {
2929 // Bail on real errors.
2936 'charset' => $charset,
2937 'length' => $this->get_col_length( $table, $column ),
2941 $data = $this->strip_invalid_text( $data );
2942 if ( is_wp_error( $data ) ) {
2946 return $data[ $column ]['value'];
2950 * Find the first table name referenced in a query.
2955 * @param string $query The query to search.
2956 * @return string|false $table The table name found, or false if a table couldn't be found.
2958 protected function get_table_from_query( $query ) {
2959 // Remove characters that can legally trail the table name.
2960 $query = rtrim( $query, ';/-#' );
2962 // Allow (select...) union [...] style queries. Use the first query's table name.
2963 $query = ltrim( $query, "\r\n\t (" );
2965 // Strip everything between parentheses except nested selects.
2966 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
2968 // Quickly match most common queries.
2969 if ( preg_match( '/^\s*(?:'
2970 . 'SELECT.*?\s+FROM'
2971 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
2972 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
2973 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
2974 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
2975 . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
2976 return str_replace( '`', '', $maybe[1] );
2979 // SHOW TABLE STATUS and SHOW TABLES
2980 if ( preg_match( '/^\s*(?:'
2981 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2982 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2983 . ')\W((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
2984 return str_replace( '`', '', $maybe[1] );
2987 // Big pattern for the rest of the table-related queries.
2988 if ( preg_match( '/^\s*(?:'
2989 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
2990 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
2991 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
2992 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
2993 . '|TRUNCATE(?:\s+TABLE)?'
2994 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
2995 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
2996 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
2997 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
2998 . '|DROP\s+INDEX.*\s+ON'
2999 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
3000 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
3001 . '|SHOW\s+(?:.*FROM|.*TABLE)'
3002 . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
3003 return str_replace( '`', '', $maybe[1] );
3010 * Load the column metadata from the last query.
3016 protected function load_col_info() {
3017 if ( $this->col_info )
3020 if ( $this->use_mysqli ) {
3021 $num_fields = mysqli_num_fields( $this->result );
3022 for ( $i = 0; $i < $num_fields; $i++ ) {
3023 $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
3026 $num_fields = mysql_num_fields( $this->result );
3027 for ( $i = 0; $i < $num_fields; $i++ ) {
3028 $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
3034 * Retrieve column metadata from the last query.
3038 * @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
3039 * @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
3040 * @return mixed Column Results
3042 public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
3043 $this->load_col_info();
3045 if ( $this->col_info ) {
3046 if ( $col_offset == -1 ) {
3048 $new_array = array();
3049 foreach ( (array) $this->col_info as $col ) {
3050 $new_array[$i] = $col->{$info_type};
3055 return $this->col_info[$col_offset]->{$info_type};
3061 * Starts the timer, for debugging purposes.
3067 public function timer_start() {
3068 $this->time_start = microtime( true );
3073 * Stops the debugging timer.
3077 * @return float Total time spent on the query, in seconds
3079 public function timer_stop() {
3080 return ( microtime( true ) - $this->time_start );
3084 * Wraps errors in a nice header and footer and dies.
3086 * Will not die if wpdb::$show_errors is false.
3090 * @param string $message The Error message
3091 * @param string $error_code Optional. A Computer readable string to identify the error.
3092 * @return false|void
3094 public function bail( $message, $error_code = '500' ) {
3095 if ( !$this->show_errors ) {
3096 if ( class_exists( 'WP_Error', false ) ) {
3097 $this->error = new WP_Error($error_code, $message);
3099 $this->error = $message;
3108 * Closes the current database connection.
3113 * @return bool True if the connection was successfully closed, false if it wasn't,
3114 * or the connection doesn't exist.
3116 public function close() {
3117 if ( ! $this->dbh ) {
3121 if ( $this->use_mysqli ) {
3122 $closed = mysqli_close( $this->dbh );
3124 $closed = mysql_close( $this->dbh );
3129 $this->ready = false;
3130 $this->has_connected = false;
3137 * Whether MySQL database is at least the required minimum version.
3141 * @global string $wp_version
3142 * @global string $required_mysql_version
3144 * @return WP_Error|void
3146 public function check_database_version() {
3147 global $wp_version, $required_mysql_version;
3148 // Make sure the server has the required MySQL version
3149 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
3150 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
3154 * Whether the database supports collation.
3156 * Called when WordPress is generating the table scheme.
3158 * Use `wpdb::has_cap( 'collation' )`.
3161 * @deprecated 3.5.0 Use wpdb::has_cap()
3163 * @return bool True if collation is supported, false if version does not
3165 public function supports_collation() {
3166 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
3167 return $this->has_cap( 'collation' );
3171 * The database character collate.
3175 * @return string The database character collate.
3177 public function get_charset_collate() {
3178 $charset_collate = '';
3180 if ( ! empty( $this->charset ) )
3181 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
3182 if ( ! empty( $this->collate ) )
3183 $charset_collate .= " COLLATE $this->collate";
3185 return $charset_collate;
3189 * Determine if a database supports a particular feature.
3192 * @since 4.1.0 Support was added for the 'utf8mb4' feature.
3194 * @see wpdb::db_version()
3196 * @param string $db_cap The feature to check for. Accepts 'collation',
3197 * 'group_concat', 'subqueries', 'set_charset',
3199 * @return int|false Whether the database feature is supported, false otherwise.
3201 public function has_cap( $db_cap ) {
3202 $version = $this->db_version();
3204 switch ( strtolower( $db_cap ) ) {
3205 case 'collation' : // @since 2.5.0
3206 case 'group_concat' : // @since 2.7.0
3207 case 'subqueries' : // @since 2.7.0
3208 return version_compare( $version, '4.1', '>=' );
3209 case 'set_charset' :
3210 return version_compare( $version, '5.0.7', '>=' );
3211 case 'utf8mb4' : // @since 4.1.0
3212 if ( version_compare( $version, '5.5.3', '<' ) ) {
3215 if ( $this->use_mysqli ) {
3216 $client_version = mysqli_get_client_info();
3218 $client_version = mysql_get_client_info();
3222 * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
3223 * mysqlnd has supported utf8mb4 since 5.0.9.
3225 if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
3226 $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
3227 return version_compare( $client_version, '5.0.9', '>=' );
3229 return version_compare( $client_version, '5.5.3', '>=' );
3237 * Retrieve the name of the function that called wpdb.
3239 * Searches up the list of functions until it reaches
3240 * the one that would most logically had called this method.
3244 * @return string|array The name of the calling function
3246 public function get_caller() {
3247 return wp_debug_backtrace_summary( __CLASS__ );
3251 * Retrieves the MySQL server version.
3255 * @return null|string Null on failure, version number on success.
3257 public function db_version() {
3258 if ( $this->use_mysqli ) {
3259 $server_info = mysqli_get_server_info( $this->dbh );
3261 $server_info = mysql_get_server_info( $this->dbh );
3263 return preg_replace( '/[^0-9.].*/', '', $server_info );