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
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).
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', '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 * Global and Multisite tables
390 * WordPress User Metadata table
399 * WordPress Users table
408 * Multisite Blogs table
417 * Multisite Blog Versions table
423 public $blog_versions;
426 * Multisite Registration Log table
432 public $registration_log;
435 * Multisite Signups table
444 * Multisite Sites table
453 * Multisite Sitewide Terms table
459 public $sitecategories;
462 * Multisite Site Metadata table
471 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
473 * Keys are column names, values are format types: 'ID' => '%d'
476 * @see wpdb::prepare()
477 * @see wpdb::insert()
478 * @see wpdb::update()
479 * @see wpdb::delete()
480 * @see wp_set_wpdb_vars()
484 public $field_types = array();
487 * Database table columns charset
496 * Database table columns collate
520 protected $dbpassword;
550 * A textual description of the last query/get_row/get_var call
559 * Whether MySQL is used as the database engine.
561 * Set in WPDB::db_connect() to true, by default. This is used when checking
562 * against the required MySQL version for WordPress. Normally, a replacement
563 * database drop-in (db.php) will skip these checks, but setting this to true
564 * will force the checks to occur.
570 public $is_mysql = null;
573 * A list of incompatible SQL modes.
579 protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
580 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
583 * Whether to use mysqli over mysql.
589 private $use_mysqli = false;
592 * Whether we've managed to successfully connect at some point
598 private $has_connected = false;
601 * Connects to the database server and selects a database
603 * PHP5 style constructor for compatibility with PHP5. Does
604 * the actual setting up of the class properties and connection
607 * @link https://core.trac.wordpress.org/ticket/3354
610 * @param string $dbuser MySQL database user
611 * @param string $dbpassword MySQL database password
612 * @param string $dbname MySQL database name
613 * @param string $dbhost MySQL database host
615 public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
616 register_shutdown_function( array( $this, '__destruct' ) );
618 if ( WP_DEBUG && WP_DEBUG_DISPLAY )
619 $this->show_errors();
621 /* Use ext/mysqli if it exists and:
622 * - WP_USE_EXT_MYSQL is defined as false, or
623 * - We are a development version of WordPress, or
624 * - We are running PHP 5.5 or greater, or
625 * - ext/mysql is not loaded.
627 if ( function_exists( 'mysqli_connect' ) ) {
628 if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
629 $this->use_mysqli = ! WP_USE_EXT_MYSQL;
630 } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
631 $this->use_mysqli = true;
632 } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
633 $this->use_mysqli = true;
637 $this->dbuser = $dbuser;
638 $this->dbpassword = $dbpassword;
639 $this->dbname = $dbname;
640 $this->dbhost = $dbhost;
642 // wp-config.php creation will manually connect when ready.
643 if ( defined( 'WP_SETUP_CONFIG' ) ) {
651 * PHP5 style destructor and will run when database object is destroyed.
653 * @see wpdb::__construct()
657 public function __destruct() {
662 * PHP5 style magic getter, used to lazy-load expensive data.
666 * @param string $name The private member to get, and optionally process
667 * @return mixed The private member
669 public function __get( $name ) {
670 if ( 'col_info' === $name )
671 $this->load_col_info();
677 * Magic function, for backwards compatibility.
681 * @param string $name The private member to set
682 * @param mixed $value The value to set
684 public function __set( $name, $value ) {
685 $protected_members = array(
688 'check_current_query',
690 if ( in_array( $name, $protected_members, true ) ) {
693 $this->$name = $value;
697 * Magic function, for backwards compatibility.
701 * @param string $name The private member to check
703 * @return bool If the member is set or not
705 public function __isset( $name ) {
706 return isset( $this->$name );
710 * Magic function, for backwards compatibility.
714 * @param string $name The private member to unset
716 public function __unset( $name ) {
717 unset( $this->$name );
721 * Set $this->charset and $this->collate
725 public function init_charset() {
726 if ( function_exists('is_multisite') && is_multisite() ) {
727 $this->charset = 'utf8';
728 if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
729 $this->collate = DB_COLLATE;
731 $this->collate = 'utf8_general_ci';
733 } elseif ( defined( 'DB_COLLATE' ) ) {
734 $this->collate = DB_COLLATE;
737 if ( defined( 'DB_CHARSET' ) ) {
738 $this->charset = DB_CHARSET;
741 if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) )
742 || ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) ) {
746 if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
747 $this->charset = 'utf8mb4';
750 if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
751 $this->collate = 'utf8mb4_unicode_ci';
756 * Sets the connection's character set.
760 * @param resource $dbh The resource given by mysql_connect
761 * @param string $charset Optional. The character set. Default null.
762 * @param string $collate Optional. The collation. Default null.
764 public function set_charset( $dbh, $charset = null, $collate = null ) {
765 if ( ! isset( $charset ) )
766 $charset = $this->charset;
767 if ( ! isset( $collate ) )
768 $collate = $this->collate;
769 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
770 if ( $this->use_mysqli ) {
771 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
772 mysqli_set_charset( $dbh, $charset );
774 $query = $this->prepare( 'SET NAMES %s', $charset );
775 if ( ! empty( $collate ) )
776 $query .= $this->prepare( ' COLLATE %s', $collate );
777 mysqli_query( $dbh, $query );
780 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
781 mysql_set_charset( $charset, $dbh );
783 $query = $this->prepare( 'SET NAMES %s', $charset );
784 if ( ! empty( $collate ) )
785 $query .= $this->prepare( ' COLLATE %s', $collate );
786 mysql_query( $query, $dbh );
793 * Change the current SQL mode, and ensure its WordPress compatibility.
795 * If no modes are passed, it will ensure the current MySQL server
796 * modes are compatible.
800 * @param array $modes Optional. A list of SQL modes to set.
802 public function set_sql_mode( $modes = array() ) {
803 if ( empty( $modes ) ) {
804 if ( $this->use_mysqli ) {
805 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
807 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
810 if ( empty( $res ) ) {
814 if ( $this->use_mysqli ) {
815 $modes_array = mysqli_fetch_array( $res );
816 if ( empty( $modes_array[0] ) ) {
819 $modes_str = $modes_array[0];
821 $modes_str = mysql_result( $res, 0 );
824 if ( empty( $modes_str ) ) {
828 $modes = explode( ',', $modes_str );
831 $modes = array_change_key_case( $modes, CASE_UPPER );
834 * Filter the list of incompatible SQL modes to exclude.
838 * @param array $incompatible_modes An array of incompatible modes.
840 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
842 foreach( $modes as $i => $mode ) {
843 if ( in_array( $mode, $incompatible_modes ) ) {
844 unset( $modes[ $i ] );
848 $modes_str = implode( ',', $modes );
850 if ( $this->use_mysqli ) {
851 mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
853 mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
858 * Sets the table prefix for the WordPress tables.
862 * @param string $prefix Alphanumeric name for the new prefix.
863 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
864 * @return string|WP_Error Old prefix or WP_Error on error
866 public function set_prefix( $prefix, $set_table_names = true ) {
868 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
869 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
871 $old_prefix = is_multisite() ? '' : $prefix;
873 if ( isset( $this->base_prefix ) )
874 $old_prefix = $this->base_prefix;
876 $this->base_prefix = $prefix;
878 if ( $set_table_names ) {
879 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
880 $this->$table = $prefixed_table;
882 if ( is_multisite() && empty( $this->blogid ) )
885 $this->prefix = $this->get_blog_prefix();
887 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
888 $this->$table = $prefixed_table;
890 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
891 $this->$table = $prefixed_table;
901 * @param int $blog_id
902 * @param int $site_id Optional.
903 * @return int previous blog id
905 public function set_blog_id( $blog_id, $site_id = 0 ) {
906 if ( ! empty( $site_id ) )
907 $this->siteid = $site_id;
909 $old_blog_id = $this->blogid;
910 $this->blogid = $blog_id;
912 $this->prefix = $this->get_blog_prefix();
914 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
915 $this->$table = $prefixed_table;
917 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
918 $this->$table = $prefixed_table;
927 * @param int $blog_id Optional.
928 * @return string Blog prefix.
930 public function get_blog_prefix( $blog_id = null ) {
931 if ( is_multisite() ) {
932 if ( null === $blog_id )
933 $blog_id = $this->blogid;
934 $blog_id = (int) $blog_id;
935 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
936 return $this->base_prefix;
938 return $this->base_prefix . $blog_id . '_';
940 return $this->base_prefix;
945 * Returns an array of WordPress tables.
947 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
948 * override the WordPress users and usermeta tables that would otherwise
949 * be determined by the prefix.
951 * The scope argument can take one of the following:
953 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
954 * 'blog' - returns the blog-level tables for the queried blog.
955 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
956 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
957 * 'old' - returns tables which are deprecated.
960 * @uses wpdb::$tables
961 * @uses wpdb::$old_tables
962 * @uses wpdb::$global_tables
963 * @uses wpdb::$ms_global_tables
965 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
966 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
967 * prefix is requested, then the custom users and usermeta tables will be mapped.
968 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
969 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
971 public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
974 $tables = array_merge( $this->global_tables, $this->tables );
975 if ( is_multisite() )
976 $tables = array_merge( $tables, $this->ms_global_tables );
979 $tables = $this->tables;
982 $tables = $this->global_tables;
983 if ( is_multisite() )
984 $tables = array_merge( $tables, $this->ms_global_tables );
987 $tables = $this->ms_global_tables;
990 $tables = $this->old_tables;
998 $blog_id = $this->blogid;
999 $blog_prefix = $this->get_blog_prefix( $blog_id );
1000 $base_prefix = $this->base_prefix;
1001 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
1002 foreach ( $tables as $k => $table ) {
1003 if ( in_array( $table, $global_tables ) )
1004 $tables[ $table ] = $base_prefix . $table;
1006 $tables[ $table ] = $blog_prefix . $table;
1007 unset( $tables[ $k ] );
1010 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
1011 $tables['users'] = CUSTOM_USER_TABLE;
1013 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
1014 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
1021 * Selects a database using the current database connection.
1023 * The database name will be changed based on the current database
1024 * connection. On failure, the execution will bail and display an DB error.
1028 * @param string $db MySQL database name
1029 * @param resource $dbh Optional link identifier.
1030 * @return null Always null.
1032 public function select( $db, $dbh = null ) {
1033 if ( is_null($dbh) )
1036 if ( $this->use_mysqli ) {
1037 $success = @mysqli_select_db( $dbh, $db );
1039 $success = @mysql_select_db( $db, $dbh );
1042 $this->ready = false;
1043 if ( ! did_action( 'template_redirect' ) ) {
1044 wp_load_translations_early();
1045 $this->bail( sprintf( __( '<h1>Can’t select database</h1>
1046 <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
1048 <li>Are you sure it exists?</li>
1049 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
1050 <li>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?</li>
1052 <p>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="https://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
1059 * Do not use, deprecated.
1061 * Use esc_sql() or wpdb::prepare() instead.
1065 * @see wpdb::prepare
1069 * @param string $string
1072 function _weak_escape( $string ) {
1073 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1074 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1075 return addslashes( $string );
1079 * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1081 * @see mysqli_real_escape_string()
1082 * @see mysql_real_escape_string()
1086 * @param string $string to escape
1087 * @return string escaped
1089 function _real_escape( $string ) {
1091 if ( $this->use_mysqli ) {
1092 return mysqli_real_escape_string( $this->dbh, $string );
1094 return mysql_real_escape_string( $string, $this->dbh );
1098 $class = get_class( $this );
1099 if ( function_exists( '__' ) ) {
1100 _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
1102 _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
1104 return addslashes( $string );
1108 * Escape data. Works on arrays.
1110 * @uses wpdb::_real_escape()
1114 * @param string|array $data
1115 * @return string|array escaped
1117 function _escape( $data ) {
1118 if ( is_array( $data ) ) {
1119 foreach ( $data as $k => $v ) {
1121 $data[$k] = $this->_escape( $v );
1123 $data[$k] = $this->_real_escape( $v );
1126 $data = $this->_real_escape( $data );
1133 * Do not use, deprecated.
1135 * Use esc_sql() or wpdb::prepare() instead.
1139 * @see wpdb::prepare()
1142 * @param mixed $data
1145 public function escape( $data ) {
1146 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1147 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1148 if ( is_array( $data ) ) {
1149 foreach ( $data as $k => $v ) {
1150 if ( is_array( $v ) )
1151 $data[$k] = $this->escape( $v, 'recursive' );
1153 $data[$k] = $this->_weak_escape( $v, 'internal' );
1156 $data = $this->_weak_escape( $data, 'internal' );
1163 * Escapes content by reference for insertion into the database, for security
1165 * @uses wpdb::_real_escape()
1167 * @param string $string to escape
1170 public function escape_by_ref( &$string ) {
1171 if ( ! is_float( $string ) )
1172 $string = $this->_real_escape( $string );
1176 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1178 * The following directives can be used in the query format string:
1182 * %% (literal percentage sign - no argument needed)
1184 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1185 * Literals (%) as parts of the query must be properly written as %%.
1187 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1188 * Does not support sign, padding, alignment, width or precision specifiers.
1189 * Does not support argument numbering/swapping.
1191 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
1193 * Both %d and %s should be left unquoted in the query string.
1195 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1196 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1198 * @link http://php.net/sprintf Description of syntax.
1201 * @param string $query Query statement with sprintf()-like placeholders
1202 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1203 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1204 * being called like {@link http://php.net/sprintf sprintf()}.
1205 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1206 * {@link http://php.net/sprintf sprintf()}.
1207 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
1208 * if there was something to prepare
1210 public function prepare( $query, $args ) {
1211 if ( is_null( $query ) )
1214 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1215 if ( strpos( $query, '%' ) === false ) {
1216 _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
1219 $args = func_get_args();
1220 array_shift( $args );
1221 // If args were passed as an array (as in vsprintf), move them up
1222 if ( isset( $args[0] ) && is_array($args[0]) )
1224 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1225 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1226 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1227 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1228 array_walk( $args, array( $this, 'escape_by_ref' ) );
1229 return @vsprintf( $query, $args );
1233 * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1235 * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1237 * Example Prepared Statement:
1239 * $find = 'only 43% of planets';
1240 * $like = $wild . $wpdb->esc_like( $find ) . $wild;
1241 * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
1243 * Example Escape Chain:
1244 * $sql = esc_sql( $wpdb->esc_like( $input ) );
1249 * @param string $text The raw text to be escaped. The input typed by the user should have no
1250 * extra or deleted slashes.
1251 * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1252 * or real_escape next.
1254 public function esc_like( $text ) {
1255 return addcslashes( $text, '_%\\' );
1259 * Print SQL/DB error.
1262 * @global array $EZSQL_ERROR Stores error information of query and error string
1264 * @param string $str The error to display
1265 * @return false|null False if the showing of errors is disabled.
1267 public function print_error( $str = '' ) {
1268 global $EZSQL_ERROR;
1271 if ( $this->use_mysqli ) {
1272 $str = mysqli_error( $this->dbh );
1274 $str = mysql_error( $this->dbh );
1277 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1279 if ( $this->suppress_errors )
1282 wp_load_translations_early();
1284 if ( $caller = $this->get_caller() )
1285 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1287 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1289 error_log( $error_str );
1291 // Are we showing errors?
1292 if ( ! $this->show_errors )
1295 // If there is an error then take note of it
1296 if ( is_multisite() ) {
1297 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1298 if ( defined( 'ERRORLOGFILE' ) )
1299 error_log( $msg, 3, ERRORLOGFILE );
1300 if ( defined( 'DIEONDBERROR' ) )
1303 $str = htmlspecialchars( $str, ENT_QUOTES );
1304 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1306 print "<div id='error'>
1307 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1308 <code>$query</code></p>
1314 * Enables showing of database errors.
1316 * This function should be used only to enable showing of errors.
1317 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1318 * this function can be used to enable and disable showing of database
1322 * @see wpdb::hide_errors()
1324 * @param bool $show Whether to show or hide errors
1325 * @return bool Old value for showing errors.
1327 public function show_errors( $show = true ) {
1328 $errors = $this->show_errors;
1329 $this->show_errors = $show;
1334 * Disables showing of database errors.
1336 * By default database errors are not shown.
1339 * @see wpdb::show_errors()
1341 * @return bool Whether showing of errors was active
1343 public function hide_errors() {
1344 $show = $this->show_errors;
1345 $this->show_errors = false;
1350 * Whether to suppress database errors.
1352 * By default database errors are suppressed, with a simple
1353 * call to this function they can be enabled.
1356 * @see wpdb::hide_errors()
1357 * @param bool $suppress Optional. New value. Defaults to true.
1358 * @return bool Old value
1360 public function suppress_errors( $suppress = true ) {
1361 $errors = $this->suppress_errors;
1362 $this->suppress_errors = (bool) $suppress;
1367 * Kill cached query results.
1372 public function flush() {
1373 $this->last_result = array();
1374 $this->col_info = null;
1375 $this->last_query = null;
1376 $this->rows_affected = $this->num_rows = 0;
1377 $this->last_error = '';
1379 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1380 mysqli_free_result( $this->result );
1381 $this->result = null;
1383 // Sanity check before using the handle
1384 if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1388 // Clear out any results from a multi-query
1389 while ( mysqli_more_results( $this->dbh ) ) {
1390 mysqli_next_result( $this->dbh );
1392 } elseif ( is_resource( $this->result ) ) {
1393 mysql_free_result( $this->result );
1398 * Connect to and select database.
1400 * If $allow_bail is false, the lack of database connection will need
1401 * to be handled manually.
1404 * @since 3.9.0 $allow_bail parameter added.
1406 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1407 * @return null|bool True with a successful connection, false on failure.
1409 public function db_connect( $allow_bail = true ) {
1411 $this->is_mysql = true;
1414 * Deprecated in 3.9+ when using MySQLi. No equivalent
1415 * $new_link parameter exists for mysqli_* functions.
1417 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1418 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1420 if ( $this->use_mysqli ) {
1421 $this->dbh = mysqli_init();
1423 // mysqli_real_connect doesn't support the host param including a port or socket
1424 // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1427 $host = $this->dbhost;
1428 $port_or_socket = strstr( $host, ':' );
1429 if ( ! empty( $port_or_socket ) ) {
1430 $host = substr( $host, 0, strpos( $host, ':' ) );
1431 $port_or_socket = substr( $port_or_socket, 1 );
1432 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1433 $port = intval( $port_or_socket );
1434 $maybe_socket = strstr( $port_or_socket, ':' );
1435 if ( ! empty( $maybe_socket ) ) {
1436 $socket = substr( $maybe_socket, 1 );
1439 $socket = $port_or_socket;
1444 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1446 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1449 if ( $this->dbh->connect_errno ) {
1452 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1453 * - We haven't previously connected, and
1454 * - WP_USE_EXT_MYSQL isn't set to false, and
1455 * - ext/mysql is loaded.
1457 $attempt_fallback = true;
1459 if ( $this->has_connected ) {
1460 $attempt_fallback = false;
1461 } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1462 $attempt_fallback = false;
1463 } elseif ( ! function_exists( 'mysql_connect' ) ) {
1464 $attempt_fallback = false;
1467 if ( $attempt_fallback ) {
1468 $this->use_mysqli = false;
1469 $this->db_connect();
1474 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1476 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1480 if ( ! $this->dbh && $allow_bail ) {
1481 wp_load_translations_early();
1483 // Load custom DB error template, if present.
1484 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1485 require_once( WP_CONTENT_DIR . '/db-error.php' );
1489 $this->bail( sprintf( __( "
1490 <h1>Error establishing a database connection</h1>
1491 <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>
1493 <li>Are you sure you have the correct username and password?</li>
1494 <li>Are you sure that you have typed the correct hostname?</li>
1495 <li>Are you sure that the database server is running?</li>
1497 <p>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='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
1498 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1501 } elseif ( $this->dbh ) {
1502 if ( ! $this->has_connected ) {
1503 $this->init_charset();
1506 $this->has_connected = true;
1508 $this->set_charset( $this->dbh );
1510 $this->ready = true;
1511 $this->set_sql_mode();
1512 $this->select( $this->dbname, $this->dbh );
1521 * Check that the connection to the database is still up. If not, try to reconnect.
1523 * If this function is unable to reconnect, it will forcibly die, or if after the
1524 * the template_redirect hook has been fired, return false instead.
1526 * If $allow_bail is false, the lack of database connection will need
1527 * to be handled manually.
1531 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1532 * @return bool|null True if the connection is up.
1534 public function check_connection( $allow_bail = true ) {
1535 if ( $this->use_mysqli ) {
1536 if ( @mysqli_ping( $this->dbh ) ) {
1540 if ( @mysql_ping( $this->dbh ) ) {
1545 $error_reporting = false;
1547 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1549 $error_reporting = error_reporting();
1550 error_reporting( $error_reporting & ~E_WARNING );
1553 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1554 // On the last try, re-enable warnings. We want to see a single instance of the
1555 // "unable to connect" message on the bail() screen, if it appears.
1556 if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1557 error_reporting( $error_reporting );
1560 if ( $this->db_connect( false ) ) {
1561 if ( $error_reporting ) {
1562 error_reporting( $error_reporting );
1571 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1572 // Let's just return and hope for the best.
1573 if ( did_action( 'template_redirect' ) ) {
1577 if ( ! $allow_bail ) {
1581 // We weren't able to reconnect, so we better bail.
1582 $this->bail( sprintf( ( "
1583 <h1>Error reconnecting to the database</h1>
1584 <p>This means that we lost contact with the database server at <code>%s</code>. This could mean your host's database server is down.</p>
1586 <li>Are you sure that the database server is running?</li>
1587 <li>Are you sure that the database server is not under particularly heavy load?</li>
1589 <p>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='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
1590 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1592 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1597 * Perform a MySQL database query, using current database connection.
1599 * More information can be found on the codex page.
1603 * @param string $query Database query
1604 * @return int|false Number of rows affected/selected or false on error
1606 public function query( $query ) {
1607 if ( ! $this->ready ) {
1608 $this->check_current_query = true;
1613 * Filter the database query.
1615 * Some queries are made before the plugins have been loaded,
1616 * and thus cannot be filtered with this method.
1620 * @param string $query Database query.
1622 $query = apply_filters( 'query', $query );
1626 // Log how the function was called
1627 $this->func_call = "\$db->query(\"$query\")";
1629 // If we're writing to the database, make sure the query will write safely.
1630 if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
1631 $stripped_query = $this->strip_invalid_text_from_query( $query );
1632 // strip_invalid_text_from_query() can perform queries, so we need
1633 // to flush again, just to make sure everything is clear.
1635 if ( $stripped_query !== $query ) {
1636 $this->insert_id = 0;
1641 $this->check_current_query = true;
1643 // Keep track of the last query for debug..
1644 $this->last_query = $query;
1646 $this->_do_query( $query );
1648 // MySQL server has gone away, try to reconnect
1650 if ( ! empty( $this->dbh ) ) {
1651 if ( $this->use_mysqli ) {
1652 $mysql_errno = mysqli_errno( $this->dbh );
1654 $mysql_errno = mysql_errno( $this->dbh );
1658 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1659 if ( $this->check_connection() ) {
1660 $this->_do_query( $query );
1662 $this->insert_id = 0;
1667 // If there is an error then take note of it..
1668 if ( $this->use_mysqli ) {
1669 $this->last_error = mysqli_error( $this->dbh );
1671 $this->last_error = mysql_error( $this->dbh );
1674 if ( $this->last_error ) {
1675 // Clear insert_id on a subsequent failed insert.
1676 if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1677 $this->insert_id = 0;
1679 $this->print_error();
1683 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1684 $return_val = $this->result;
1685 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1686 if ( $this->use_mysqli ) {
1687 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1689 $this->rows_affected = mysql_affected_rows( $this->dbh );
1691 // Take note of the insert_id
1692 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1693 if ( $this->use_mysqli ) {
1694 $this->insert_id = mysqli_insert_id( $this->dbh );
1696 $this->insert_id = mysql_insert_id( $this->dbh );
1699 // Return number of rows affected
1700 $return_val = $this->rows_affected;
1703 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1704 while ( $row = @mysqli_fetch_object( $this->result ) ) {
1705 $this->last_result[$num_rows] = $row;
1708 } elseif ( is_resource( $this->result ) ) {
1709 while ( $row = @mysql_fetch_object( $this->result ) ) {
1710 $this->last_result[$num_rows] = $row;
1715 // Log number of rows the query returned
1716 // and return number of rows selected
1717 $this->num_rows = $num_rows;
1718 $return_val = $num_rows;
1725 * Internal function to perform the mysql_query() call.
1730 * @see wpdb::query()
1732 * @param string $query The query to run.
1734 private function _do_query( $query ) {
1735 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1736 $this->timer_start();
1739 if ( $this->use_mysqli ) {
1740 $this->result = @mysqli_query( $this->dbh, $query );
1742 $this->result = @mysql_query( $query, $this->dbh );
1744 $this->num_queries++;
1746 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1747 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1752 * Insert a row into a table.
1754 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1755 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1758 * @see wpdb::prepare()
1759 * @see wpdb::$field_types
1760 * @see wp_set_wpdb_vars()
1762 * @param string $table table name
1763 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1764 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
1765 * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1766 * @return int|false The number of rows inserted, or false on error.
1768 public function insert( $table, $data, $format = null ) {
1769 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1773 * Replace a row into a table.
1775 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1776 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1779 * @see wpdb::prepare()
1780 * @see wpdb::$field_types
1781 * @see wp_set_wpdb_vars()
1783 * @param string $table table name
1784 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1785 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
1786 * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1787 * @return int|false The number of rows affected, or false on error.
1789 public function replace( $table, $data, $format = null ) {
1790 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1794 * Helper function for insert and replace.
1796 * Runs an insert or replace query based on $type argument.
1800 * @see wpdb::prepare()
1801 * @see wpdb::$field_types
1802 * @see wp_set_wpdb_vars()
1804 * @param string $table table name
1805 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1806 * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
1807 * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1808 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1809 * @return int|false The number of rows affected, or false on error.
1811 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1812 $this->insert_id = 0;
1814 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
1818 $data = $this->process_fields( $table, $data, $format );
1819 if ( false === $data ) {
1823 $formats = $values = array();
1824 foreach ( $data as $value ) {
1825 $formats[] = $value['format'];
1826 $values[] = $value['value'];
1829 $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
1830 $formats = implode( ', ', $formats );
1832 $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
1834 $this->check_current_query = false;
1835 return $this->query( $this->prepare( $sql, $values ) );
1839 * Update a row in the table
1841 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1842 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1845 * @see wpdb::prepare()
1846 * @see wpdb::$field_types
1847 * @see wp_set_wpdb_vars()
1849 * @param string $table table name
1850 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1851 * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
1852 * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data.
1853 * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1854 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings.
1855 * @return int|false The number of rows updated, or false on error.
1857 public function update( $table, $data, $where, $format = null, $where_format = null ) {
1858 if ( ! is_array( $data ) || ! is_array( $where ) ) {
1862 $data = $this->process_fields( $table, $data, $format );
1863 if ( false === $data ) {
1866 $where = $this->process_fields( $table, $where, $where_format );
1867 if ( false === $where ) {
1871 $fields = $conditions = $values = array();
1872 foreach ( $data as $field => $value ) {
1873 $fields[] = "`$field` = " . $value['format'];
1874 $values[] = $value['value'];
1876 foreach ( $where as $field => $value ) {
1877 $conditions[] = "`$field` = " . $value['format'];
1878 $values[] = $value['value'];
1881 $fields = implode( ', ', $fields );
1882 $conditions = implode( ' AND ', $conditions );
1884 $sql = "UPDATE `$table` SET $fields WHERE $conditions";
1886 $this->check_current_query = false;
1887 return $this->query( $this->prepare( $sql, $values ) );
1891 * Delete a row in the table
1893 * wpdb::delete( 'table', array( 'ID' => 1 ) )
1894 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1897 * @see wpdb::prepare()
1898 * @see wpdb::$field_types
1899 * @see wp_set_wpdb_vars()
1901 * @param string $table table name
1902 * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
1903 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
1904 * @return int|false The number of rows updated, or false on error.
1906 public function delete( $table, $where, $where_format = null ) {
1907 if ( ! is_array( $where ) ) {
1911 $where = $this->process_fields( $table, $where, $where_format );
1912 if ( false === $where ) {
1916 $conditions = $values = array();
1917 foreach ( $where as $field => $value ) {
1918 $conditions[] = "`$field` = " . $value['format'];
1919 $values[] = $value['value'];
1922 $conditions = implode( ' AND ', $conditions );
1924 $sql = "DELETE FROM `$table` WHERE $conditions";
1926 $this->check_current_query = false;
1927 return $this->query( $this->prepare( $sql, $values ) );
1931 * Processes arrays of field/value pairs and field formats.
1933 * This is a helper method for wpdb's CRUD methods, which take field/value
1934 * pairs for inserts, updates, and where clauses. This method first pairs
1935 * each value with a format. Then it determines the charset of that field,
1936 * using that to determine if any invalid text would be stripped. If text is
1937 * stripped, then field processing is rejected and the query fails.
1942 * @param string $table Table name.
1943 * @param array $data Field/value pair.
1944 * @param mixed $format Format for each field.
1945 * @return array|bool Returns an array of fields that contain paired values
1946 * and formats. Returns false for invalid values.
1948 protected function process_fields( $table, $data, $format ) {
1949 $data = $this->process_field_formats( $data, $format );
1950 if ( false === $data ) {
1954 $data = $this->process_field_charsets( $data, $table );
1955 if ( false === $data ) {
1959 $data = $this->process_field_lengths( $data, $table );
1960 if ( false === $data ) {
1964 $converted_data = $this->strip_invalid_text( $data );
1966 if ( $data !== $converted_data ) {
1974 * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
1979 * @param array $data Array of fields to values.
1980 * @param mixed $format Formats to be mapped to the values in $data.
1981 * @return array Array, keyed by field names with values being an array
1982 * of 'value' and 'format' keys.
1984 protected function process_field_formats( $data, $format ) {
1985 $formats = $original_formats = (array) $format;
1987 foreach ( $data as $field => $value ) {
1993 if ( ! empty( $format ) ) {
1994 $value['format'] = array_shift( $formats );
1995 if ( ! $value['format'] ) {
1996 $value['format'] = reset( $original_formats );
1998 } elseif ( isset( $this->field_types[ $field ] ) ) {
1999 $value['format'] = $this->field_types[ $field ];
2002 $data[ $field ] = $value;
2009 * Adds field charsets to field/value/format arrays generated by
2010 * the wpdb::process_field_formats() method.
2015 * @param array $data As it comes from the wpdb::process_field_formats() method.
2016 * @param string $table Table name.
2017 * @return The same array as $data with additional 'charset' keys.
2019 protected function process_field_charsets( $data, $table ) {
2020 foreach ( $data as $field => $value ) {
2021 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2022 // We can skip this field if we know it isn't a string.
2023 // This checks %d/%f versus ! %s because it's sprintf() could take more.
2024 $value['charset'] = false;
2026 $value['charset'] = $this->get_col_charset( $table, $field );
2027 if ( is_wp_error( $value['charset'] ) ) {
2032 $data[ $field ] = $value;
2039 * For string fields, record the maximum string length that field can safely save.
2044 * @param array $data As it comes from the wpdb::process_field_charsets() method.
2045 * @param string $table Table name.
2046 * @return array|False The same array as $data with additional 'length' keys, or false if
2047 * any of the values were too long for their corresponding field.
2049 protected function process_field_lengths( $data, $table ) {
2050 foreach ( $data as $field => $value ) {
2051 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2052 // We can skip this field if we know it isn't a string.
2053 // This checks %d/%f versus ! %s because it's sprintf() could take more.
2054 $value['length'] = false;
2056 $value['length'] = $this->get_col_length( $table, $field );
2057 if ( is_wp_error( $value['length'] ) ) {
2062 $data[ $field ] = $value;
2069 * Retrieve one variable from the database.
2071 * Executes a SQL query and returns the value from the SQL result.
2072 * 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.
2073 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2077 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2078 * @param int $x Optional. Column of value to return. Indexed from 0.
2079 * @param int $y Optional. Row of value to return. Indexed from 0.
2080 * @return string|null Database query result (as string), or null on failure
2082 public function get_var( $query = null, $x = 0, $y = 0 ) {
2083 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2085 if ( $this->check_safe_collation( $query ) ) {
2086 $this->check_current_query = false;
2090 $this->query( $query );
2093 // Extract var out of cached results based x,y vals
2094 if ( !empty( $this->last_result[$y] ) ) {
2095 $values = array_values( get_object_vars( $this->last_result[$y] ) );
2098 // If there is a value return it else return null
2099 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2103 * Retrieve one row from the database.
2105 * Executes a SQL query and returns the row from the SQL result.
2109 * @param string|null $query SQL query.
2110 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
2111 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
2112 * @param int $y Optional. Row to return. Indexed from 0.
2113 * @return mixed Database query result in format specified by $output or null on failure
2115 public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2116 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2118 if ( $this->check_safe_collation( $query ) ) {
2119 $this->check_current_query = false;
2123 $this->query( $query );
2128 if ( !isset( $this->last_result[$y] ) )
2131 if ( $output == OBJECT ) {
2132 return $this->last_result[$y] ? $this->last_result[$y] : null;
2133 } elseif ( $output == ARRAY_A ) {
2134 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2135 } elseif ( $output == ARRAY_N ) {
2136 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2137 } elseif ( strtoupper( $output ) === OBJECT ) {
2138 // Back compat for OBJECT being previously case insensitive.
2139 return $this->last_result[$y] ? $this->last_result[$y] : null;
2141 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2146 * Retrieve one column from the database.
2148 * Executes a SQL query and returns the column from the SQL result.
2149 * If the SQL result contains more than one column, this function returns the column specified.
2150 * If $query is null, this function returns the specified column from the previous SQL result.
2154 * @param string|null $query Optional. SQL query. Defaults to previous query.
2155 * @param int $x Optional. Column to return. Indexed from 0.
2156 * @return array Database query result. Array indexed from 0 by SQL result row number.
2158 public function get_col( $query = null , $x = 0 ) {
2159 if ( $this->check_safe_collation( $query ) ) {
2160 $this->check_current_query = false;
2164 $this->query( $query );
2167 $new_array = array();
2168 // Extract the column values
2169 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2170 $new_array[$i] = $this->get_var( null, $x, $i );
2176 * Retrieve an entire SQL result set from the database (i.e., many rows)
2178 * Executes a SQL query and returns the entire SQL result.
2182 * @param string $query SQL query.
2183 * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number.
2184 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2185 * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded.
2186 * @return mixed Database query results
2188 public function get_results( $query = null, $output = OBJECT ) {
2189 $this->func_call = "\$db->get_results(\"$query\", $output)";
2191 if ( $this->check_safe_collation( $query ) ) {
2192 $this->check_current_query = false;
2196 $this->query( $query );
2201 $new_array = array();
2202 if ( $output == OBJECT ) {
2203 // Return an integer-keyed array of row objects
2204 return $this->last_result;
2205 } elseif ( $output == OBJECT_K ) {
2206 // Return an array of row objects with keys from column 1
2207 // (Duplicates are discarded)
2208 foreach ( $this->last_result as $row ) {
2209 $var_by_ref = get_object_vars( $row );
2210 $key = array_shift( $var_by_ref );
2211 if ( ! isset( $new_array[ $key ] ) )
2212 $new_array[ $key ] = $row;
2215 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2216 // Return an integer-keyed array of...
2217 if ( $this->last_result ) {
2218 foreach( (array) $this->last_result as $row ) {
2219 if ( $output == ARRAY_N ) {
2220 // ...integer-keyed row arrays
2221 $new_array[] = array_values( get_object_vars( $row ) );
2223 // ...column name-keyed row arrays
2224 $new_array[] = get_object_vars( $row );
2229 } elseif ( strtoupper( $output ) === OBJECT ) {
2230 // Back compat for OBJECT being previously case insensitive.
2231 return $this->last_result;
2237 * Retrieves the character set for the given table.
2242 * @param string $table Table name.
2243 * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
2245 protected function get_table_charset( $table ) {
2246 $tablekey = strtolower( $table );
2249 * Filter the table charset value before the DB is checked.
2251 * Passing a non-null value to the filter will effectively short-circuit
2252 * checking the DB for the charset, returning that value instead.
2256 * @param string $charset The character set to use. Default null.
2257 * @param string $table The name of the table being checked.
2259 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2260 if ( null !== $charset ) {
2264 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2265 return $this->table_charset[ $tablekey ];
2268 $charsets = $columns = array();
2270 $table_parts = explode( '.', $table );
2271 $table = '`' . implode( '`.`', $table_parts ) . '`';
2272 $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
2274 return new WP_Error( 'wpdb_get_table_charset_failure' );
2277 foreach ( $results as $column ) {
2278 $columns[ strtolower( $column->Field ) ] = $column;
2281 $this->col_meta[ $tablekey ] = $columns;
2283 foreach ( $columns as $column ) {
2284 if ( ! empty( $column->Collation ) ) {
2285 list( $charset ) = explode( '_', $column->Collation );
2287 // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
2288 if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
2292 $charsets[ strtolower( $charset ) ] = true;
2295 list( $type ) = explode( '(', $column->Type );
2297 // A binary/blob means the whole query gets treated like this.
2298 if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2299 $this->table_charset[ $tablekey ] = 'binary';
2304 // utf8mb3 is an alias for utf8.
2305 if ( isset( $charsets['utf8mb3'] ) ) {
2306 $charsets['utf8'] = true;
2307 unset( $charsets['utf8mb3'] );
2310 // Check if we have more than one charset in play.
2311 $count = count( $charsets );
2312 if ( 1 === $count ) {
2313 $charset = key( $charsets );
2314 } elseif ( 0 === $count ) {
2315 // No charsets, assume this table can store whatever.
2318 // More than one charset. Remove latin1 if present and recalculate.
2319 unset( $charsets['latin1'] );
2320 $count = count( $charsets );
2321 if ( 1 === $count ) {
2322 // Only one charset (besides latin1).
2323 $charset = key( $charsets );
2324 } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2325 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2328 // Two mixed character sets. ascii.
2333 $this->table_charset[ $tablekey ] = $charset;
2338 * Retrieves the character set for the given column.
2343 * @param string $table Table name.
2344 * @param string $column Column name.
2345 * @return mixed Column character set as a string. False if the column has no
2346 * character set. WP_Error object if there was an error.
2348 public function get_col_charset( $table, $column ) {
2349 $tablekey = strtolower( $table );
2350 $columnkey = strtolower( $column );
2353 * Filter the column charset value before the DB is checked.
2355 * Passing a non-null value to the filter will short-circuit
2356 * checking the DB for the charset, returning that value instead.
2360 * @param string $charset The character set to use. Default null.
2361 * @param string $table The name of the table being checked.
2362 * @param string $column The name of the column being checked.
2364 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2365 if ( null !== $charset ) {
2369 // Skip this entirely if this isn't a MySQL database.
2370 if ( false === $this->is_mysql ) {
2374 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2375 // This primes column information for us.
2376 $table_charset = $this->get_table_charset( $table );
2377 if ( is_wp_error( $table_charset ) ) {
2378 return $table_charset;
2382 // If still no column information, return the table charset.
2383 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2384 return $this->table_charset[ $tablekey ];
2387 // If this column doesn't exist, return the table charset.
2388 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2389 return $this->table_charset[ $tablekey ];
2392 // Return false when it's not a string column.
2393 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2397 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2402 * Retrieve the maximum string length allowed in a given column.
2403 * The length may either be specified as a byte length or a character length.
2408 * @param string $table Table name.
2409 * @param string $column Column name.
2410 * @return mixed array( 'length' => (int), 'type' => 'byte' | 'char' )
2411 * false if the column has no length (for example, numeric column)
2412 * WP_Error object if there was an error.
2414 public function get_col_length( $table, $column ) {
2415 $tablekey = strtolower( $table );
2416 $columnkey = strtolower( $column );
2418 // Skip this entirely if this isn't a MySQL database.
2419 if ( false === $this->is_mysql ) {
2423 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2424 // This primes column information for us.
2425 $table_charset = $this->get_table_charset( $table );
2426 if ( is_wp_error( $table_charset ) ) {
2427 return $table_charset;
2431 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2435 $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
2437 $type = strtolower( $typeinfo[0] );
2438 if ( ! empty( $typeinfo[1] ) ) {
2439 $length = trim( $typeinfo[1], ')' );
2449 'length' => (int) $length,
2456 'length' => (int) $length,
2463 'length' => 255, // 2^8 - 1
2470 'length' => 65535, // 2^16 - 1
2477 'length' => 16777215, // 2^24 - 1
2484 'length' => 4294967295, // 2^32 - 1
2495 * Check if a string is ASCII.
2497 * The negative regex is faster for non-ASCII strings, as it allows
2498 * the search to finish as soon as it encounters a non-ASCII character.
2503 * @param string $string String to check.
2504 * @return bool True if ASCII, false if not.
2506 protected function check_ascii( $string ) {
2507 if ( function_exists( 'mb_check_encoding' ) ) {
2508 if ( mb_check_encoding( $string, 'ASCII' ) ) {
2511 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2519 * Check if the query is accessing a collation considered safe on the current version of MySQL.
2524 * @param string $query The query to check.
2525 * @return bool True if the collation is safe, false if it isn't.
2527 protected function check_safe_collation( $query ) {
2528 if ( $this->checking_collation ) {
2532 // We don't need to check the collation for queries that don't read data.
2533 $query = ltrim( $query, "\r\n\t (" );
2534 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
2538 // All-ASCII queries don't need extra checking.
2539 if ( $this->check_ascii( $query ) ) {
2543 $table = $this->get_table_from_query( $query );
2548 $this->checking_collation = true;
2549 $collation = $this->get_table_charset( $table );
2550 $this->checking_collation = false;
2552 // Tables with no collation, or latin1 only, don't need extra checking.
2553 if ( false === $collation || 'latin1' === $collation ) {
2557 $table = strtolower( $table );
2558 if ( empty( $this->col_meta[ $table ] ) ) {
2562 // If any of the columns don't have one of these collations, it needs more sanity checking.
2563 foreach( $this->col_meta[ $table ] as $col ) {
2564 if ( empty( $col->Collation ) ) {
2568 if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2577 * Strips any invalid characters based on value/charset pairs.
2582 * @param array $data Array of value arrays. Each value array has the keys
2583 * 'value' and 'charset'. An optional 'ascii' key can be
2584 * set to false to avoid redundant ASCII checks.
2585 * @return array|WP_Error The $data parameter, with invalid characters removed from
2586 * each value. This works as a passthrough: any additional keys
2587 * such as 'field' are retained in each value array. If we cannot
2588 * remove invalid characters, a WP_Error object is returned.
2590 protected function strip_invalid_text( $data ) {
2591 $db_check_string = false;
2593 foreach ( $data as &$value ) {
2594 $charset = $value['charset'];
2596 if ( is_array( $value['length'] ) ) {
2597 $length = $value['length']['length'];
2602 // There's no charset to work with.
2603 if ( false === $charset ) {
2607 // Column isn't a string.
2608 if ( ! is_string( $value['value'] ) ) {
2612 $truncate_by_byte_length = 'byte' === $value['length']['type'];
2614 $needs_validation = true;
2616 // latin1 can store any byte sequence
2617 'latin1' === $charset
2619 // ASCII is always OK.
2620 ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
2622 $truncate_by_byte_length = true;
2623 $needs_validation = false;
2626 if ( $truncate_by_byte_length ) {
2627 mbstring_binary_safe_encoding();
2628 if ( false !== $length && strlen( $value['value'] ) > $length ) {
2629 $value['value'] = substr( $value['value'], 0, $length );
2631 reset_mbstring_encoding();
2633 if ( ! $needs_validation ) {
2638 // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2639 if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
2642 (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
2643 | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
2644 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
2645 | [\xE1-\xEC][\x80-\xBF]{2}
2646 | \xED[\x80-\x9F][\x80-\xBF]
2647 | [\xEE-\xEF][\x80-\xBF]{2}';
2649 if ( 'utf8mb4' === $charset ) {
2651 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
2652 | [\xF1-\xF3][\x80-\xBF]{3}
2653 | \xF4[\x80-\x8F][\x80-\xBF]{2}
2657 $regex .= '){1,40} # ...one or more times
2661 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2664 if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
2665 $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
2670 // We couldn't use any local conversions, send it to the DB.
2671 $value['db'] = $db_check_string = true;
2673 unset( $value ); // Remove by reference.
2675 if ( $db_check_string ) {
2677 foreach ( $data as $col => $value ) {
2678 if ( ! empty( $value['db'] ) ) {
2679 if ( ! isset( $queries[ $value['charset'] ] ) ) {
2680 $queries[ $value['charset'] ] = array();
2683 // We're going to need to truncate by characters or bytes, depending on the length value we have.
2684 if ( 'byte' === $value['length']['type'] ) {
2685 // Split the CONVERT() calls by charset, so we can make sure the connection is right
2686 $queries[ $value['charset'] ][ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING binary ), %d ) USING {$value['charset']} )", $value['value'], $value['length']['length'] );
2688 $queries[ $value['charset'] ][ $col ] = $this->prepare( "LEFT( CONVERT( %s USING {$value['charset']} ), %d )", $value['value'], $value['length']['length'] );
2691 unset( $data[ $col ]['db'] );
2695 $connection_charset = $this->charset;
2696 foreach ( $queries as $charset => $query ) {
2701 // Change the charset to match the string(s) we're converting
2702 if ( $charset !== $connection_charset ) {
2703 $connection_charset = $charset;
2704 $this->set_charset( $this->dbh, $charset );
2707 $this->check_current_query = false;
2710 foreach ( $query as $column => $column_query ) {
2711 $sql[] = $column_query . " AS x_$column";
2714 $row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
2716 $this->set_charset( $this->dbh, $connection_charset );
2717 return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2720 foreach ( array_keys( $query ) as $column ) {
2721 $data[ $column ]['value'] = $row["x_$column"];
2725 // Don't forget to change the charset back!
2726 if ( $connection_charset !== $this->charset ) {
2727 $this->set_charset( $this->dbh );
2735 * Strips any invalid characters from the query.
2740 * @param string $query Query to convert.
2741 * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
2743 protected function strip_invalid_text_from_query( $query ) {
2744 // We don't need to check the collation for queries that don't read data.
2745 $trimmed_query = ltrim( $query, "\r\n\t (" );
2746 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
2750 $table = $this->get_table_from_query( $query );
2752 $charset = $this->get_table_charset( $table );
2753 if ( is_wp_error( $charset ) ) {
2757 // We can't reliably strip text from tables containing binary/blob columns
2758 if ( 'binary' === $charset ) {
2762 $charset = $this->charset;
2767 'charset' => $charset,
2772 $data = $this->strip_invalid_text( array( $data ) );
2773 if ( is_wp_error( $data ) ) {
2777 return $data[0]['value'];
2781 * Strips any invalid characters from the string for a given table and column.
2786 * @param string $table Table name.
2787 * @param string $column Column name.
2788 * @param string $value The text to check.
2789 * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
2791 public function strip_invalid_text_for_column( $table, $column, $value ) {
2792 if ( ! is_string( $value ) ) {
2796 $charset = $this->get_col_charset( $table, $column );
2798 // Not a string column.
2800 } elseif ( is_wp_error( $charset ) ) {
2801 // Bail on real errors.
2808 'charset' => $charset,
2809 'length' => $this->get_col_length( $table, $column ),
2813 $data = $this->strip_invalid_text( $data );
2814 if ( is_wp_error( $data ) ) {
2818 return $data[ $column ]['value'];
2822 * Find the first table name referenced in a query.
2827 * @param string $query The query to search.
2828 * @return string|false $table The table name found, or false if a table couldn't be found.
2830 protected function get_table_from_query( $query ) {
2831 // Remove characters that can legally trail the table name.
2832 $query = rtrim( $query, ';/-#' );
2834 // Allow (select...) union [...] style queries. Use the first query's table name.
2835 $query = ltrim( $query, "\r\n\t (" );
2838 * Strip everything between parentheses except nested selects and use only 1,000
2839 * chars of the query.
2841 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $query, 0, 1000 ) );
2843 // Quickly match most common queries.
2844 if ( preg_match( '/^\s*(?:'
2845 . 'SELECT.*?\s+FROM'
2846 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
2847 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
2848 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
2849 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
2850 . ')\s+((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
2851 return str_replace( '`', '', $maybe[1] );
2854 // SHOW TABLE STATUS and SHOW TABLES
2855 if ( preg_match( '/^\s*(?:'
2856 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2857 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2858 . ')\W((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
2859 return str_replace( '`', '', $maybe[1] );
2862 // Big pattern for the rest of the table-related queries.
2863 if ( preg_match( '/^\s*(?:'
2864 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
2865 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
2866 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
2867 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
2868 . '|TRUNCATE(?:\s+TABLE)?'
2869 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
2870 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
2871 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
2872 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
2873 . '|DROP\s+INDEX.*\s+ON'
2874 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
2875 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
2876 . '|SHOW\s+(?:.*FROM|.*TABLE)'
2877 . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
2878 return str_replace( '`', '', $maybe[1] );
2885 * Load the column metadata from the last query.
2891 protected function load_col_info() {
2892 if ( $this->col_info )
2895 if ( $this->use_mysqli ) {
2896 for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
2897 $this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
2900 for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
2901 $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
2907 * Retrieve column metadata from the last query.
2911 * @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
2912 * @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
2913 * @return mixed Column Results
2915 public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
2916 $this->load_col_info();
2918 if ( $this->col_info ) {
2919 if ( $col_offset == -1 ) {
2921 $new_array = array();
2922 foreach( (array) $this->col_info as $col ) {
2923 $new_array[$i] = $col->{$info_type};
2928 return $this->col_info[$col_offset]->{$info_type};
2934 * Starts the timer, for debugging purposes.
2940 public function timer_start() {
2941 $this->time_start = microtime( true );
2946 * Stops the debugging timer.
2950 * @return float Total time spent on the query, in seconds
2952 public function timer_stop() {
2953 return ( microtime( true ) - $this->time_start );
2957 * Wraps errors in a nice header and footer and dies.
2959 * Will not die if wpdb::$show_errors is false.
2963 * @param string $message The Error message
2964 * @param string $error_code Optional. A Computer readable string to identify the error.
2965 * @return false|void
2967 public function bail( $message, $error_code = '500' ) {
2968 if ( !$this->show_errors ) {
2969 if ( class_exists( 'WP_Error' ) )
2970 $this->error = new WP_Error($error_code, $message);
2972 $this->error = $message;
2979 * Whether MySQL database is at least the required minimum version.
2983 * @uses $required_mysql_version
2987 public function check_database_version() {
2988 global $wp_version, $required_mysql_version;
2989 // Make sure the server has the required MySQL version
2990 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
2991 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
2995 * Whether the database supports collation.
2997 * Called when WordPress is generating the table scheme.
3001 * @deprecated Use wpdb::has_cap( 'collation' )
3003 * @return bool True if collation is supported, false if version does not
3005 public function supports_collation() {
3006 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
3007 return $this->has_cap( 'collation' );
3011 * The database character collate.
3015 * @return string The database character collate.
3017 public function get_charset_collate() {
3018 $charset_collate = '';
3020 if ( ! empty( $this->charset ) )
3021 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
3022 if ( ! empty( $this->collate ) )
3023 $charset_collate .= " COLLATE $this->collate";
3025 return $charset_collate;
3029 * Determine if a database supports a particular feature.
3032 * @since 4.1.0 Support was added for the 'utf8mb4' feature.
3034 * @see wpdb::db_version()
3036 * @param string $db_cap The feature to check for. Accepts 'collation',
3037 * 'group_concat', 'subqueries', 'set_charset',
3039 * @return bool Whether the database feature is supported, false otherwise.
3041 public function has_cap( $db_cap ) {
3042 $version = $this->db_version();
3044 switch ( strtolower( $db_cap ) ) {
3045 case 'collation' : // @since 2.5.0
3046 case 'group_concat' : // @since 2.7.0
3047 case 'subqueries' : // @since 2.7.0
3048 return version_compare( $version, '4.1', '>=' );
3049 case 'set_charset' :
3050 return version_compare( $version, '5.0.7', '>=' );
3051 case 'utf8mb4' : // @since 4.1.0
3052 if ( version_compare( $version, '5.5.3', '<' ) ) {
3055 if ( $this->use_mysqli ) {
3056 $client_version = mysqli_get_client_info();
3058 $client_version = mysql_get_client_info();
3062 * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
3063 * mysqlnd has supported utf8mb4 since 5.0.9.
3065 if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
3066 $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
3067 return version_compare( $client_version, '5.0.9', '>=' );
3069 return version_compare( $client_version, '5.5.3', '>=' );
3077 * Retrieve the name of the function that called wpdb.
3079 * Searches up the list of functions until it reaches
3080 * the one that would most logically had called this method.
3084 * @return string The name of the calling function
3086 public function get_caller() {
3087 return wp_debug_backtrace_summary( __CLASS__ );
3091 * The database version number.
3095 * @return null|string Null on failure, version number on success.
3097 public function db_version() {
3098 if ( $this->use_mysqli ) {
3099 $server_info = mysqli_get_server_info( $this->dbh );
3101 $server_info = mysql_get_server_info( $this->dbh );
3103 return preg_replace( '/[^0-9.].*/', '', $server_info );