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 http://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.
243 * {@internal Missing Description}}
252 * {@internal Missing Description}}
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->init_charset();
639 $this->dbuser = $dbuser;
640 $this->dbpassword = $dbpassword;
641 $this->dbname = $dbname;
642 $this->dbhost = $dbhost;
644 // wp-config.php creation will manually connect when ready.
645 if ( defined( 'WP_SETUP_CONFIG' ) ) {
653 * PHP5 style destructor and will run when database object is destroyed.
655 * @see wpdb::__construct()
659 public function __destruct() {
664 * PHP5 style magic getter, used to lazy-load expensive data.
668 * @param string $name The private member to get, and optionally process
669 * @return mixed The private member
671 public function __get( $name ) {
672 if ( 'col_info' === $name )
673 $this->load_col_info();
679 * Magic function, for backwards compatibility.
683 * @param string $name The private member to set
684 * @param mixed $value The value to set
686 public function __set( $name, $value ) {
687 $protected_members = array(
690 'check_current_query',
692 if ( in_array( $name, $protected_members, true ) ) {
695 $this->$name = $value;
699 * Magic function, for backwards compatibility.
703 * @param string $name The private member to check
705 * @return bool If the member is set or not
707 public function __isset( $name ) {
708 return isset( $this->$name );
712 * Magic function, for backwards compatibility.
716 * @param string $name The private member to unset
718 public function __unset( $name ) {
719 unset( $this->$name );
723 * Set $this->charset and $this->collate
727 public function init_charset() {
728 if ( function_exists('is_multisite') && is_multisite() ) {
729 $this->charset = 'utf8';
730 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
731 $this->collate = DB_COLLATE;
733 $this->collate = 'utf8_general_ci';
734 } elseif ( defined( 'DB_COLLATE' ) ) {
735 $this->collate = DB_COLLATE;
738 if ( defined( 'DB_CHARSET' ) )
739 $this->charset = DB_CHARSET;
743 * Sets the connection's character set.
747 * @param resource $dbh The resource given by mysql_connect
748 * @param string $charset Optional. The character set. Default null.
749 * @param string $collate Optional. The collation. Default null.
751 public function set_charset( $dbh, $charset = null, $collate = null ) {
752 if ( ! isset( $charset ) )
753 $charset = $this->charset;
754 if ( ! isset( $collate ) )
755 $collate = $this->collate;
756 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
757 if ( $this->use_mysqli ) {
758 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
759 mysqli_set_charset( $dbh, $charset );
761 $query = $this->prepare( 'SET NAMES %s', $charset );
762 if ( ! empty( $collate ) )
763 $query .= $this->prepare( ' COLLATE %s', $collate );
764 mysqli_query( $dbh, $query );
767 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
768 mysql_set_charset( $charset, $dbh );
770 $query = $this->prepare( 'SET NAMES %s', $charset );
771 if ( ! empty( $collate ) )
772 $query .= $this->prepare( ' COLLATE %s', $collate );
773 mysql_query( $query, $dbh );
780 * Change the current SQL mode, and ensure its WordPress compatibility.
782 * If no modes are passed, it will ensure the current MySQL server
783 * modes are compatible.
787 * @param array $modes Optional. A list of SQL modes to set.
789 public function set_sql_mode( $modes = array() ) {
790 if ( empty( $modes ) ) {
791 if ( $this->use_mysqli ) {
792 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
794 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
797 if ( empty( $res ) ) {
801 if ( $this->use_mysqli ) {
802 $modes_array = mysqli_fetch_array( $res );
803 if ( empty( $modes_array[0] ) ) {
806 $modes_str = $modes_array[0];
808 $modes_str = mysql_result( $res, 0 );
811 if ( empty( $modes_str ) ) {
815 $modes = explode( ',', $modes_str );
818 $modes = array_change_key_case( $modes, CASE_UPPER );
821 * Filter the list of incompatible SQL modes to exclude.
825 * @param array $incompatible_modes An array of incompatible modes.
827 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
829 foreach( $modes as $i => $mode ) {
830 if ( in_array( $mode, $incompatible_modes ) ) {
831 unset( $modes[ $i ] );
835 $modes_str = implode( ',', $modes );
837 if ( $this->use_mysqli ) {
838 mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
840 mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
845 * Sets the table prefix for the WordPress tables.
849 * @param string $prefix Alphanumeric name for the new prefix.
850 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
851 * @return string|WP_Error Old prefix or WP_Error on error
853 public function set_prefix( $prefix, $set_table_names = true ) {
855 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
856 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
858 $old_prefix = is_multisite() ? '' : $prefix;
860 if ( isset( $this->base_prefix ) )
861 $old_prefix = $this->base_prefix;
863 $this->base_prefix = $prefix;
865 if ( $set_table_names ) {
866 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
867 $this->$table = $prefixed_table;
869 if ( is_multisite() && empty( $this->blogid ) )
872 $this->prefix = $this->get_blog_prefix();
874 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
875 $this->$table = $prefixed_table;
877 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
878 $this->$table = $prefixed_table;
888 * @param int $blog_id
889 * @param int $site_id Optional.
890 * @return int previous blog id
892 public function set_blog_id( $blog_id, $site_id = 0 ) {
893 if ( ! empty( $site_id ) )
894 $this->siteid = $site_id;
896 $old_blog_id = $this->blogid;
897 $this->blogid = $blog_id;
899 $this->prefix = $this->get_blog_prefix();
901 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
902 $this->$table = $prefixed_table;
904 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
905 $this->$table = $prefixed_table;
914 * @param int $blog_id Optional.
915 * @return string Blog prefix.
917 public function get_blog_prefix( $blog_id = null ) {
918 if ( is_multisite() ) {
919 if ( null === $blog_id )
920 $blog_id = $this->blogid;
921 $blog_id = (int) $blog_id;
922 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
923 return $this->base_prefix;
925 return $this->base_prefix . $blog_id . '_';
927 return $this->base_prefix;
932 * Returns an array of WordPress tables.
934 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
935 * override the WordPress users and usermeta tables that would otherwise
936 * be determined by the prefix.
938 * The scope argument can take one of the following:
940 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
941 * 'blog' - returns the blog-level tables for the queried blog.
942 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
943 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
944 * 'old' - returns tables which are deprecated.
947 * @uses wpdb::$tables
948 * @uses wpdb::$old_tables
949 * @uses wpdb::$global_tables
950 * @uses wpdb::$ms_global_tables
952 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
953 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
954 * prefix is requested, then the custom users and usermeta tables will be mapped.
955 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
956 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
958 public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
961 $tables = array_merge( $this->global_tables, $this->tables );
962 if ( is_multisite() )
963 $tables = array_merge( $tables, $this->ms_global_tables );
966 $tables = $this->tables;
969 $tables = $this->global_tables;
970 if ( is_multisite() )
971 $tables = array_merge( $tables, $this->ms_global_tables );
974 $tables = $this->ms_global_tables;
977 $tables = $this->old_tables;
985 $blog_id = $this->blogid;
986 $blog_prefix = $this->get_blog_prefix( $blog_id );
987 $base_prefix = $this->base_prefix;
988 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
989 foreach ( $tables as $k => $table ) {
990 if ( in_array( $table, $global_tables ) )
991 $tables[ $table ] = $base_prefix . $table;
993 $tables[ $table ] = $blog_prefix . $table;
994 unset( $tables[ $k ] );
997 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
998 $tables['users'] = CUSTOM_USER_TABLE;
1000 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
1001 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
1008 * Selects a database using the current database connection.
1010 * The database name will be changed based on the current database
1011 * connection. On failure, the execution will bail and display an DB error.
1015 * @param string $db MySQL database name
1016 * @param resource $dbh Optional link identifier.
1017 * @return null Always null.
1019 public function select( $db, $dbh = null ) {
1020 if ( is_null($dbh) )
1023 if ( $this->use_mysqli ) {
1024 $success = @mysqli_select_db( $dbh, $db );
1026 $success = @mysql_select_db( $db, $dbh );
1029 $this->ready = false;
1030 if ( ! did_action( 'template_redirect' ) ) {
1031 wp_load_translations_early();
1032 $this->bail( sprintf( __( '<h1>Can’t select database</h1>
1033 <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>
1035 <li>Are you sure it exists?</li>
1036 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
1037 <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>
1039 <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' );
1046 * Do not use, deprecated.
1048 * Use esc_sql() or wpdb::prepare() instead.
1052 * @see wpdb::prepare
1056 * @param string $string
1059 function _weak_escape( $string ) {
1060 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1061 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1062 return addslashes( $string );
1066 * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1068 * @see mysqli_real_escape_string()
1069 * @see mysql_real_escape_string()
1073 * @param string $string to escape
1074 * @return string escaped
1076 function _real_escape( $string ) {
1078 if ( $this->use_mysqli ) {
1079 return mysqli_real_escape_string( $this->dbh, $string );
1081 return mysql_real_escape_string( $string, $this->dbh );
1085 $class = get_class( $this );
1086 if ( function_exists( '__' ) ) {
1087 _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
1089 _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
1091 return addslashes( $string );
1095 * Escape data. Works on arrays.
1097 * @uses wpdb::_real_escape()
1101 * @param string|array $data
1102 * @return string|array escaped
1104 function _escape( $data ) {
1105 if ( is_array( $data ) ) {
1106 foreach ( $data as $k => $v ) {
1108 $data[$k] = $this->_escape( $v );
1110 $data[$k] = $this->_real_escape( $v );
1113 $data = $this->_real_escape( $data );
1120 * Do not use, deprecated.
1122 * Use esc_sql() or wpdb::prepare() instead.
1126 * @see wpdb::prepare()
1129 * @param mixed $data
1132 public function escape( $data ) {
1133 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1134 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1135 if ( is_array( $data ) ) {
1136 foreach ( $data as $k => $v ) {
1137 if ( is_array( $v ) )
1138 $data[$k] = $this->escape( $v, 'recursive' );
1140 $data[$k] = $this->_weak_escape( $v, 'internal' );
1143 $data = $this->_weak_escape( $data, 'internal' );
1150 * Escapes content by reference for insertion into the database, for security
1152 * @uses wpdb::_real_escape()
1154 * @param string $string to escape
1157 public function escape_by_ref( &$string ) {
1158 if ( ! is_float( $string ) )
1159 $string = $this->_real_escape( $string );
1163 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1165 * The following directives can be used in the query format string:
1169 * %% (literal percentage sign - no argument needed)
1171 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1172 * Literals (%) as parts of the query must be properly written as %%.
1174 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1175 * Does not support sign, padding, alignment, width or precision specifiers.
1176 * Does not support argument numbering/swapping.
1178 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
1180 * Both %d and %s should be left unquoted in the query string.
1182 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1183 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1185 * @link http://php.net/sprintf Description of syntax.
1188 * @param string $query Query statement with sprintf()-like placeholders
1189 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1190 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1191 * being called like {@link http://php.net/sprintf sprintf()}.
1192 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1193 * {@link http://php.net/sprintf sprintf()}.
1194 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
1195 * if there was something to prepare
1197 public function prepare( $query, $args ) {
1198 if ( is_null( $query ) )
1201 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1202 if ( strpos( $query, '%' ) === false ) {
1203 _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
1206 $args = func_get_args();
1207 array_shift( $args );
1208 // If args were passed as an array (as in vsprintf), move them up
1209 if ( isset( $args[0] ) && is_array($args[0]) )
1211 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1212 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1213 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1214 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1215 array_walk( $args, array( $this, 'escape_by_ref' ) );
1216 return @vsprintf( $query, $args );
1220 * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1222 * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1224 * Example Prepared Statement:
1226 * $find = 'only 43% of planets';
1227 * $like = $wild . $wpdb->esc_like( $find ) . $wild;
1228 * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
1230 * Example Escape Chain:
1231 * $sql = esc_sql( $wpdb->esc_like( $input ) );
1236 * @param string $text The raw text to be escaped. The input typed by the user should have no
1237 * extra or deleted slashes.
1238 * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1239 * or real_escape next.
1241 public function esc_like( $text ) {
1242 return addcslashes( $text, '_%\\' );
1246 * Print SQL/DB error.
1249 * @global array $EZSQL_ERROR Stores error information of query and error string
1251 * @param string $str The error to display
1252 * @return false|null False if the showing of errors is disabled.
1254 public function print_error( $str = '' ) {
1255 global $EZSQL_ERROR;
1258 if ( $this->use_mysqli ) {
1259 $str = mysqli_error( $this->dbh );
1261 $str = mysql_error( $this->dbh );
1264 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1266 if ( $this->suppress_errors )
1269 wp_load_translations_early();
1271 if ( $caller = $this->get_caller() )
1272 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1274 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1276 error_log( $error_str );
1278 // Are we showing errors?
1279 if ( ! $this->show_errors )
1282 // If there is an error then take note of it
1283 if ( is_multisite() ) {
1284 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1285 if ( defined( 'ERRORLOGFILE' ) )
1286 error_log( $msg, 3, ERRORLOGFILE );
1287 if ( defined( 'DIEONDBERROR' ) )
1290 $str = htmlspecialchars( $str, ENT_QUOTES );
1291 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1293 print "<div id='error'>
1294 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1295 <code>$query</code></p>
1301 * Enables showing of database errors.
1303 * This function should be used only to enable showing of errors.
1304 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1305 * this function can be used to enable and disable showing of database
1309 * @see wpdb::hide_errors()
1311 * @param bool $show Whether to show or hide errors
1312 * @return bool Old value for showing errors.
1314 public function show_errors( $show = true ) {
1315 $errors = $this->show_errors;
1316 $this->show_errors = $show;
1321 * Disables showing of database errors.
1323 * By default database errors are not shown.
1326 * @see wpdb::show_errors()
1328 * @return bool Whether showing of errors was active
1330 public function hide_errors() {
1331 $show = $this->show_errors;
1332 $this->show_errors = false;
1337 * Whether to suppress database errors.
1339 * By default database errors are suppressed, with a simple
1340 * call to this function they can be enabled.
1343 * @see wpdb::hide_errors()
1344 * @param bool $suppress Optional. New value. Defaults to true.
1345 * @return bool Old value
1347 public function suppress_errors( $suppress = true ) {
1348 $errors = $this->suppress_errors;
1349 $this->suppress_errors = (bool) $suppress;
1354 * Kill cached query results.
1359 public function flush() {
1360 $this->last_result = array();
1361 $this->col_info = null;
1362 $this->last_query = null;
1363 $this->rows_affected = $this->num_rows = 0;
1364 $this->last_error = '';
1366 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1367 mysqli_free_result( $this->result );
1368 $this->result = null;
1370 // Sanity check before using the handle
1371 if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1375 // Clear out any results from a multi-query
1376 while ( mysqli_more_results( $this->dbh ) ) {
1377 mysqli_next_result( $this->dbh );
1379 } else if ( is_resource( $this->result ) ) {
1380 mysql_free_result( $this->result );
1385 * Connect to and select database.
1387 * If $allow_bail is false, the lack of database connection will need
1388 * to be handled manually.
1391 * @since 3.9.0 $allow_bail parameter added.
1393 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1394 * @return null|bool True with a successful connection, false on failure.
1396 public function db_connect( $allow_bail = true ) {
1398 $this->is_mysql = true;
1401 * Deprecated in 3.9+ when using MySQLi. No equivalent
1402 * $new_link parameter exists for mysqli_* functions.
1404 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1405 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1407 if ( $this->use_mysqli ) {
1408 $this->dbh = mysqli_init();
1410 // mysqli_real_connect doesn't support the host param including a port or socket
1411 // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1414 $host = $this->dbhost;
1415 $port_or_socket = strstr( $host, ':' );
1416 if ( ! empty( $port_or_socket ) ) {
1417 $host = substr( $host, 0, strpos( $host, ':' ) );
1418 $port_or_socket = substr( $port_or_socket, 1 );
1419 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1420 $port = intval( $port_or_socket );
1421 $maybe_socket = strstr( $port_or_socket, ':' );
1422 if ( ! empty( $maybe_socket ) ) {
1423 $socket = substr( $maybe_socket, 1 );
1426 $socket = $port_or_socket;
1431 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1433 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1436 if ( $this->dbh->connect_errno ) {
1439 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1440 * - We haven't previously connected, and
1441 * - WP_USE_EXT_MYSQL isn't set to false, and
1442 * - ext/mysql is loaded.
1444 $attempt_fallback = true;
1446 if ( $this->has_connected ) {
1447 $attempt_fallback = false;
1448 } else if ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1449 $attempt_fallback = false;
1450 } else if ( ! function_exists( 'mysql_connect' ) ) {
1451 $attempt_fallback = false;
1454 if ( $attempt_fallback ) {
1455 $this->use_mysqli = false;
1456 $this->db_connect();
1461 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1463 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1467 if ( ! $this->dbh && $allow_bail ) {
1468 wp_load_translations_early();
1470 // Load custom DB error template, if present.
1471 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1472 require_once( WP_CONTENT_DIR . '/db-error.php' );
1476 $this->bail( sprintf( __( "
1477 <h1>Error establishing a database connection</h1>
1478 <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>
1480 <li>Are you sure you have the correct username and password?</li>
1481 <li>Are you sure that you have typed the correct hostname?</li>
1482 <li>Are you sure that the database server is running?</li>
1484 <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>
1485 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1488 } else if ( $this->dbh ) {
1489 $this->has_connected = true;
1490 $this->set_charset( $this->dbh );
1491 $this->set_sql_mode();
1492 $this->ready = true;
1493 $this->select( $this->dbname, $this->dbh );
1502 * Check that the connection to the database is still up. If not, try to reconnect.
1504 * If this function is unable to reconnect, it will forcibly die, or if after the
1505 * the template_redirect hook has been fired, return false instead.
1507 * If $allow_bail is false, the lack of database connection will need
1508 * to be handled manually.
1512 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1513 * @return bool|null True if the connection is up.
1515 public function check_connection( $allow_bail = true ) {
1516 if ( $this->use_mysqli ) {
1517 if ( @mysqli_ping( $this->dbh ) ) {
1521 if ( @mysql_ping( $this->dbh ) ) {
1526 $error_reporting = false;
1528 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1530 $error_reporting = error_reporting();
1531 error_reporting( $error_reporting & ~E_WARNING );
1534 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1535 // On the last try, re-enable warnings. We want to see a single instance of the
1536 // "unable to connect" message on the bail() screen, if it appears.
1537 if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1538 error_reporting( $error_reporting );
1541 if ( $this->db_connect( false ) ) {
1542 if ( $error_reporting ) {
1543 error_reporting( $error_reporting );
1552 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1553 // Let's just return and hope for the best.
1554 if ( did_action( 'template_redirect' ) ) {
1558 if ( ! $allow_bail ) {
1562 // We weren't able to reconnect, so we better bail.
1563 $this->bail( sprintf( ( "
1564 <h1>Error reconnecting to the database</h1>
1565 <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>
1567 <li>Are you sure that the database server is running?</li>
1568 <li>Are you sure that the database server is not under particularly heavy load?</li>
1570 <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>
1571 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1573 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1578 * Perform a MySQL database query, using current database connection.
1580 * More information can be found on the codex page.
1584 * @param string $query Database query
1585 * @return int|false Number of rows affected/selected or false on error
1587 public function query( $query ) {
1588 if ( ! $this->ready ) {
1589 $this->check_current_query = true;
1594 * Filter the database query.
1596 * Some queries are made before the plugins have been loaded,
1597 * and thus cannot be filtered with this method.
1601 * @param string $query Database query.
1603 $query = apply_filters( 'query', $query );
1607 // Log how the function was called
1608 $this->func_call = "\$db->query(\"$query\")";
1610 // If we're writing to the database, make sure the query will write safely.
1611 if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
1612 $stripped_query = $this->strip_invalid_text_from_query( $query );
1613 // strip_invalid_text_from_query() can perform queries, so we need
1614 // to flush again, just to make sure everything is clear.
1616 if ( $stripped_query !== $query ) {
1617 $this->insert_id = 0;
1622 $this->check_current_query = true;
1623 // Keep track of the last query for debug..
1624 $this->last_query = $query;
1626 $this->_do_query( $query );
1628 // MySQL server has gone away, try to reconnect
1630 if ( ! empty( $this->dbh ) ) {
1631 if ( $this->use_mysqli ) {
1632 $mysql_errno = mysqli_errno( $this->dbh );
1634 $mysql_errno = mysql_errno( $this->dbh );
1638 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1639 if ( $this->check_connection() ) {
1640 $this->_do_query( $query );
1642 $this->insert_id = 0;
1647 // If there is an error then take note of it..
1648 if ( $this->use_mysqli ) {
1649 $this->last_error = mysqli_error( $this->dbh );
1651 $this->last_error = mysql_error( $this->dbh );
1654 if ( $this->last_error ) {
1655 // Clear insert_id on a subsequent failed insert.
1656 if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1657 $this->insert_id = 0;
1659 $this->print_error();
1663 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1664 $return_val = $this->result;
1665 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1666 if ( $this->use_mysqli ) {
1667 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1669 $this->rows_affected = mysql_affected_rows( $this->dbh );
1671 // Take note of the insert_id
1672 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1673 if ( $this->use_mysqli ) {
1674 $this->insert_id = mysqli_insert_id( $this->dbh );
1676 $this->insert_id = mysql_insert_id( $this->dbh );
1679 // Return number of rows affected
1680 $return_val = $this->rows_affected;
1683 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1684 while ( $row = @mysqli_fetch_object( $this->result ) ) {
1685 $this->last_result[$num_rows] = $row;
1688 } else if ( is_resource( $this->result ) ) {
1689 while ( $row = @mysql_fetch_object( $this->result ) ) {
1690 $this->last_result[$num_rows] = $row;
1695 // Log number of rows the query returned
1696 // and return number of rows selected
1697 $this->num_rows = $num_rows;
1698 $return_val = $num_rows;
1705 * Internal function to perform the mysql_query() call.
1710 * @see wpdb::query()
1712 * @param string $query The query to run.
1714 private function _do_query( $query ) {
1715 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1716 $this->timer_start();
1719 if ( $this->use_mysqli ) {
1720 $this->result = @mysqli_query( $this->dbh, $query );
1722 $this->result = @mysql_query( $query, $this->dbh );
1724 $this->num_queries++;
1726 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1727 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1732 * Insert a row into a table.
1734 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1735 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1738 * @see wpdb::prepare()
1739 * @see wpdb::$field_types
1740 * @see wp_set_wpdb_vars()
1742 * @param string $table table name
1743 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1744 * @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.
1745 * 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.
1746 * @return int|false The number of rows inserted, or false on error.
1748 public function insert( $table, $data, $format = null ) {
1749 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1753 * Replace a row into a table.
1755 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1756 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1759 * @see wpdb::prepare()
1760 * @see wpdb::$field_types
1761 * @see wp_set_wpdb_vars()
1763 * @param string $table table name
1764 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1765 * @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.
1766 * 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.
1767 * @return int|false The number of rows affected, or false on error.
1769 public function replace( $table, $data, $format = null ) {
1770 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1774 * Helper function for insert and replace.
1776 * Runs an insert or replace query based on $type argument.
1780 * @see wpdb::prepare()
1781 * @see wpdb::$field_types
1782 * @see wp_set_wpdb_vars()
1784 * @param string $table table name
1785 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1786 * @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.
1787 * 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.
1788 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1789 * @return int|false The number of rows affected, or false on error.
1791 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1792 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
1796 $data = $this->process_fields( $table, $data, $format );
1797 if ( false === $data ) {
1801 $formats = $values = array();
1802 foreach ( $data as $value ) {
1803 $formats[] = $value['format'];
1804 $values[] = $value['value'];
1807 $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
1808 $formats = implode( ', ', $formats );
1810 $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
1812 $this->insert_id = 0;
1813 $this->check_current_query = false;
1814 return $this->query( $this->prepare( $sql, $values ) );
1818 * Update a row in the table
1820 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1821 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1824 * @see wpdb::prepare()
1825 * @see wpdb::$field_types
1826 * @see wp_set_wpdb_vars()
1828 * @param string $table table name
1829 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1830 * @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".
1831 * @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.
1832 * 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.
1833 * @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.
1834 * @return int|false The number of rows updated, or false on error.
1836 public function update( $table, $data, $where, $format = null, $where_format = null ) {
1837 if ( ! is_array( $data ) || ! is_array( $where ) ) {
1841 $data = $this->process_fields( $table, $data, $format );
1842 if ( false === $data ) {
1845 $where = $this->process_fields( $table, $where, $where_format );
1846 if ( false === $where ) {
1850 $fields = $conditions = $values = array();
1851 foreach ( $data as $field => $value ) {
1852 $fields[] = "`$field` = " . $value['format'];
1853 $values[] = $value['value'];
1855 foreach ( $where as $field => $value ) {
1856 $conditions[] = "`$field` = " . $value['format'];
1857 $values[] = $value['value'];
1860 $fields = implode( ', ', $fields );
1861 $conditions = implode( ' AND ', $conditions );
1863 $sql = "UPDATE `$table` SET $fields WHERE $conditions";
1865 $this->check_current_query = false;
1866 return $this->query( $this->prepare( $sql, $values ) );
1870 * Delete a row in the table
1872 * wpdb::delete( 'table', array( 'ID' => 1 ) )
1873 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1876 * @see wpdb::prepare()
1877 * @see wpdb::$field_types
1878 * @see wp_set_wpdb_vars()
1880 * @param string $table table name
1881 * @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".
1882 * @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.
1883 * @return int|false The number of rows updated, or false on error.
1885 public function delete( $table, $where, $where_format = null ) {
1886 if ( ! is_array( $where ) ) {
1890 $where = $this->process_fields( $table, $where, $where_format );
1891 if ( false === $where ) {
1895 $conditions = $values = array();
1896 foreach ( $where as $field => $value ) {
1897 $conditions[] = "`$field` = " . $value['format'];
1898 $values[] = $value['value'];
1901 $conditions = implode( ' AND ', $conditions );
1903 $sql = "DELETE FROM `$table` WHERE $conditions";
1905 $this->check_current_query = false;
1906 return $this->query( $this->prepare( $sql, $values ) );
1910 * Processes arrays of field/value pairs and field formats.
1912 * This is a helper method for wpdb's CRUD methods, which take field/value
1913 * pairs for inserts, updates, and where clauses. This method first pairs
1914 * each value with a format. Then it determines the charset of that field,
1915 * using that to determine if any invalid text would be stripped. If text is
1916 * stripped, then field processing is rejected and the query fails.
1921 * @param string $table Table name.
1922 * @param array $data Field/value pair.
1923 * @param mixed $format Format for each field.
1924 * @return array|bool Returns an array of fields that contain paired values
1925 * and formats. Returns false for invalid values.
1927 protected function process_fields( $table, $data, $format ) {
1928 $data = $this->process_field_formats( $data, $format );
1929 $data = $this->process_field_charsets( $data, $table );
1930 if ( false === $data ) {
1934 $converted_data = $this->strip_invalid_text( $data );
1936 if ( $data !== $converted_data ) {
1944 * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
1949 * @param array $data Array of fields to values.
1950 * @param mixed $format Formats to be mapped to the values in $data.
1951 * @return array Array, keyed by field names with values being an array
1952 * of 'value' and 'format' keys.
1954 protected function process_field_formats( $data, $format ) {
1955 $formats = $original_formats = (array) $format;
1957 foreach ( $data as $field => $value ) {
1963 if ( ! empty( $format ) ) {
1964 $value['format'] = array_shift( $formats );
1965 if ( ! $value['format'] ) {
1966 $value['format'] = reset( $original_formats );
1968 } elseif ( isset( $this->field_types[ $field ] ) ) {
1969 $value['format'] = $this->field_types[ $field ];
1972 $data[ $field ] = $value;
1979 * Adds field charsets to field/value/format arrays generated by
1980 * the {@see wpdb::process_field_formats()} method.
1985 * @param array $data As it comes from the {@see wpdb::process_field_formats()} method.
1986 * @param string $table Table name.
1987 * @return The same array as $data with additional 'charset' keys.
1989 protected function process_field_charsets( $data, $table ) {
1990 foreach ( $data as $field => $value ) {
1991 if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
1992 // We can skip this field if we know it isn't a string.
1993 // This checks %d/%f versus ! %s because it's sprintf() could take more.
1994 $value['charset'] = false;
1995 } elseif ( $this->check_ascii( $value['value'] ) ) {
1996 // If it's ASCII, then we don't need the charset. We can skip this field.
1997 $value['charset'] = false;
1999 $value['charset'] = $this->get_col_charset( $table, $field );
2000 if ( is_wp_error( $value['charset'] ) ) {
2004 // This isn't ASCII. Don't have strip_invalid_text() re-check.
2005 $value['ascii'] = false;
2008 $data[ $field ] = $value;
2015 * Retrieve one variable from the database.
2017 * Executes a SQL query and returns the value from the SQL result.
2018 * 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.
2019 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2023 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2024 * @param int $x Optional. Column of value to return. Indexed from 0.
2025 * @param int $y Optional. Row of value to return. Indexed from 0.
2026 * @return string|null Database query result (as string), or null on failure
2028 public function get_var( $query = null, $x = 0, $y = 0 ) {
2029 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2031 if ( $this->check_safe_collation( $query ) ) {
2032 $this->check_current_query = false;
2036 $this->query( $query );
2039 // Extract var out of cached results based x,y vals
2040 if ( !empty( $this->last_result[$y] ) ) {
2041 $values = array_values( get_object_vars( $this->last_result[$y] ) );
2044 // If there is a value return it else return null
2045 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2049 * Retrieve one row from the database.
2051 * Executes a SQL query and returns the row from the SQL result.
2055 * @param string|null $query SQL query.
2056 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
2057 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
2058 * @param int $y Optional. Row to return. Indexed from 0.
2059 * @return mixed Database query result in format specified by $output or null on failure
2061 public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2062 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2064 if ( $this->check_safe_collation( $query ) ) {
2065 $this->check_current_query = false;
2069 $this->query( $query );
2074 if ( !isset( $this->last_result[$y] ) )
2077 if ( $output == OBJECT ) {
2078 return $this->last_result[$y] ? $this->last_result[$y] : null;
2079 } elseif ( $output == ARRAY_A ) {
2080 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2081 } elseif ( $output == ARRAY_N ) {
2082 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2083 } elseif ( strtoupper( $output ) === OBJECT ) {
2084 // Back compat for OBJECT being previously case insensitive.
2085 return $this->last_result[$y] ? $this->last_result[$y] : null;
2087 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2092 * Retrieve one column from the database.
2094 * Executes a SQL query and returns the column from the SQL result.
2095 * If the SQL result contains more than one column, this function returns the column specified.
2096 * If $query is null, this function returns the specified column from the previous SQL result.
2100 * @param string|null $query Optional. SQL query. Defaults to previous query.
2101 * @param int $x Optional. Column to return. Indexed from 0.
2102 * @return array Database query result. Array indexed from 0 by SQL result row number.
2104 public function get_col( $query = null , $x = 0 ) {
2105 if ( $this->check_safe_collation( $query ) ) {
2106 $this->check_current_query = false;
2110 $this->query( $query );
2113 $new_array = array();
2114 // Extract the column values
2115 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2116 $new_array[$i] = $this->get_var( null, $x, $i );
2122 * Retrieve an entire SQL result set from the database (i.e., many rows)
2124 * Executes a SQL query and returns the entire SQL result.
2128 * @param string $query SQL query.
2129 * @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.
2130 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2131 * 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.
2132 * @return mixed Database query results
2134 public function get_results( $query = null, $output = OBJECT ) {
2135 $this->func_call = "\$db->get_results(\"$query\", $output)";
2137 if ( $this->check_safe_collation( $query ) ) {
2138 $this->check_current_query = false;
2142 $this->query( $query );
2147 $new_array = array();
2148 if ( $output == OBJECT ) {
2149 // Return an integer-keyed array of row objects
2150 return $this->last_result;
2151 } elseif ( $output == OBJECT_K ) {
2152 // Return an array of row objects with keys from column 1
2153 // (Duplicates are discarded)
2154 foreach ( $this->last_result as $row ) {
2155 $var_by_ref = get_object_vars( $row );
2156 $key = array_shift( $var_by_ref );
2157 if ( ! isset( $new_array[ $key ] ) )
2158 $new_array[ $key ] = $row;
2161 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2162 // Return an integer-keyed array of...
2163 if ( $this->last_result ) {
2164 foreach( (array) $this->last_result as $row ) {
2165 if ( $output == ARRAY_N ) {
2166 // ...integer-keyed row arrays
2167 $new_array[] = array_values( get_object_vars( $row ) );
2169 // ...column name-keyed row arrays
2170 $new_array[] = get_object_vars( $row );
2175 } elseif ( strtoupper( $output ) === OBJECT ) {
2176 // Back compat for OBJECT being previously case insensitive.
2177 return $this->last_result;
2183 * Retrieves the character set for the given table.
2188 * @param string $table Table name.
2189 * @return string|WP_Error Table character set, {@see WP_Error} object if it couldn't be found.
2191 protected function get_table_charset( $table ) {
2192 $tablekey = strtolower( $table );
2195 * Filter the table charset value before the DB is checked.
2197 * Passing a non-null value to the filter will effectively short-circuit
2198 * checking the DB for the charset, returning that value instead.
2202 * @param string $charset The character set to use. Default null.
2203 * @param string $table The name of the table being checked.
2205 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2206 if ( null !== $charset ) {
2210 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2211 return $this->table_charset[ $tablekey ];
2214 $charsets = $columns = array();
2215 $results = $this->get_results( "SHOW FULL COLUMNS FROM `$table`" );
2217 return new WP_Error( 'wpdb_get_table_charset_failure' );
2220 foreach ( $results as $column ) {
2221 $columns[ strtolower( $column->Field ) ] = $column;
2224 $this->col_meta[ $tablekey ] = $columns;
2226 foreach ( $columns as $column ) {
2227 if ( ! empty( $column->Collation ) ) {
2228 list( $charset ) = explode( '_', $column->Collation );
2229 $charsets[ strtolower( $charset ) ] = true;
2232 list( $type ) = explode( '(', $column->Type );
2234 // A binary/blob means the whole query gets treated like this.
2235 if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2236 $this->table_charset[ $tablekey ] = 'binary';
2241 // utf8mb3 is an alias for utf8.
2242 if ( isset( $charsets['utf8mb3'] ) ) {
2243 $charsets['utf8'] = true;
2244 unset( $charsets['utf8mb3'] );
2247 // Check if we have more than one charset in play.
2248 $count = count( $charsets );
2249 if ( 1 === $count ) {
2250 $charset = key( $charsets );
2251 } elseif ( 0 === $count ) {
2252 // No charsets, assume this table can store whatever.
2255 // More than one charset. Remove latin1 if present and recalculate.
2256 unset( $charsets['latin1'] );
2257 $count = count( $charsets );
2258 if ( 1 === $count ) {
2259 // Only one charset (besides latin1).
2260 $charset = key( $charsets );
2261 } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2262 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2265 // Two mixed character sets. ascii.
2270 $this->table_charset[ $tablekey ] = $charset;
2275 * Retrieves the character set for the given column.
2280 * @param string $table Table name.
2281 * @param string $column Column name.
2282 * @return mixed Column character set as a string. False if the column has no
2283 * character set. {@see WP_Error} object if there was an error.
2285 public function get_col_charset( $table, $column ) {
2286 $tablekey = strtolower( $table );
2287 $columnkey = strtolower( $column );
2290 * Filter the column charset value before the DB is checked.
2292 * Passing a non-null value to the filter will short-circuit
2293 * checking the DB for the charset, returning that value instead.
2297 * @param string $charset The character set to use. Default null.
2298 * @param string $table The name of the table being checked.
2299 * @param string $column The name of the column being checked.
2301 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2302 if ( null !== $charset ) {
2306 // Skip this entirely if this isn't a MySQL database.
2307 if ( false === $this->is_mysql ) {
2311 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2312 // This primes column information for us.
2313 $table_charset = $this->get_table_charset( $table );
2314 if ( is_wp_error( $table_charset ) ) {
2315 return $table_charset;
2319 // If still no column information, return the table charset.
2320 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2321 return $this->table_charset[ $tablekey ];
2324 // If this column doesn't exist, return the table charset.
2325 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2326 return $this->table_charset[ $tablekey ];
2329 // Return false when it's not a string column.
2330 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2334 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2339 * Check if a string is ASCII.
2341 * The negative regex is faster for non-ASCII strings, as it allows
2342 * the search to finish as soon as it encounters a non-ASCII character.
2347 * @param string $string String to check.
2348 * @return bool True if ASCII, false if not.
2350 protected function check_ascii( $string ) {
2351 if ( function_exists( 'mb_check_encoding' ) ) {
2352 if ( mb_check_encoding( $string, 'ASCII' ) ) {
2355 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2363 * Check if the query is accessing a collation considered safe on the current version of MySQL.
2368 * @param string $query The query to check.
2369 * @return bool True if the collation is safe, false if it isn't.
2371 protected function check_safe_collation( $query ) {
2372 if ( $this->checking_collation ) {
2376 // We don't need to check the collation for queries that don't read data.
2377 $query = ltrim( $query, "\r\n\t (" );
2378 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN)\s/i', $query ) ) {
2382 // All-ASCII queries don't need extra checking.
2383 if ( $this->check_ascii( $query ) ) {
2387 $table = $this->get_table_from_query( $query );
2392 $this->checking_collation = true;
2393 $collation = $this->get_table_charset( $table );
2394 $this->checking_collation = false;
2396 // Tables with no collation, or latin1 only, don't need extra checking.
2397 if ( false === $collation || 'latin1' === $collation ) {
2401 $table = strtolower( $table );
2402 if ( empty( $this->col_meta[ $table ] ) ) {
2406 // If any of the columns don't have one of these collations, it needs more sanity checking.
2407 foreach( $this->col_meta[ $table ] as $col ) {
2408 if ( empty( $col->Collation ) ) {
2412 if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2421 * Strips any invalid characters based on value/charset pairs.
2426 * @param array $data Array of value arrays. Each value array has the keys
2427 * 'value' and 'charset'. An optional 'ascii' key can be
2428 * set to false to avoid redundant ASCII checks.
2429 * @return array|WP_Error The $data parameter, with invalid characters removed from
2430 * each value. This works as a passthrough: any additional keys
2431 * such as 'field' are retained in each value array. If we cannot
2432 * remove invalid characters, a {@see WP_Error} object is returned.
2434 // If any of the columns don't have one of these collations, it needs more sanity checking.
2435 protected function strip_invalid_text( $data ) {
2436 // Some multibyte character sets that we can check in PHP.
2437 $mb_charsets = array(
2440 'eucjpms' => 'eucJP-win',
2441 'gb2312' => 'EUC-CN',
2443 'utf32' => 'UTF-32',
2446 $supported_charsets = array();
2447 if ( function_exists( 'mb_list_encodings' ) ) {
2448 $supported_charsets = mb_list_encodings();
2451 $db_check_string = false;
2453 foreach ( $data as &$value ) {
2454 $charset = $value['charset'];
2456 // Column isn't a string, or is latin1, which will will happily store anything.
2457 if ( false === $charset || 'latin1' === $charset ) {
2461 if ( ! is_string( $value['value'] ) ) {
2465 // ASCII is always OK.
2466 if ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) ) {
2470 // Convert the text locally.
2471 if ( $supported_charsets ) {
2472 if ( isset( $mb_charsets[ $charset ] ) && in_array( $mb_charsets[ $charset ], $supported_charsets ) ) {
2473 $value['value'] = mb_convert_encoding( $value['value'], $mb_charsets[ $charset ], $mb_charsets[ $charset ] );
2478 // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2479 if ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) {
2482 (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
2483 | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
2484 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
2485 | [\xE1-\xEC][\x80-\xBF]{2}
2486 | \xED[\x80-\x9F][\x80-\xBF]
2487 | [\xEE-\xEF][\x80-\xBF]{2}';
2489 if ( 'utf8mb4' === $charset) {
2491 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
2492 | [\xF1-\xF3][\x80-\xBF]{3}
2493 | \xF4[\x80-\x8F][\x80-\xBF]{2}
2497 $regex .= '){1,50} # ...one or more times
2501 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2505 // We couldn't use any local conversions, send it to the DB.
2506 $value['db'] = $db_check_string = true;
2508 unset( $value ); // Remove by reference.
2510 if ( $db_check_string ) {
2512 foreach ( $data as $col => $value ) {
2513 if ( ! empty( $value['db'] ) ) {
2514 if ( ! isset( $queries[ $value['charset'] ] ) ) {
2515 $queries[ $value['charset'] ] = array();
2518 // Split the CONVERT() calls by charset, so we can make sure the connection is right
2519 $queries[ $value['charset'] ][ $col ] = $this->prepare( "CONVERT( %s USING {$value['charset']} )", $value['value'] );
2523 $connection_charset = $this->charset;
2524 foreach ( $queries as $charset => $query ) {
2529 // Change the charset to match the string(s) we're converting
2530 if ( $charset !== $connection_charset ) {
2531 $connection_charset = $charset;
2532 $this->set_charset( $this->dbh, $charset );
2535 $this->check_current_query = false;
2537 $row = $this->get_row( "SELECT " . implode( ', ', $query ), ARRAY_N );
2539 $this->set_charset( $this->dbh, $connection_charset );
2540 return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2543 $cols = array_keys( $query );
2544 $col_count = count( $cols );
2545 for ( $ii = 0; $ii < $col_count; $ii++ ) {
2546 $data[ $cols[ $ii ] ]['value'] = $row[ $ii ];
2550 // Don't forget to change the charset back!
2551 if ( $connection_charset !== $this->charset ) {
2552 $this->set_charset( $this->dbh );
2560 * Strips any invalid characters from the query.
2565 * @param string $query Query to convert.
2566 * @return string|WP_Error The converted query, or a {@see WP_Error} object if the conversion fails.
2568 protected function strip_invalid_text_from_query( $query ) {
2569 $table = $this->get_table_from_query( $query );
2571 $charset = $this->get_table_charset( $table );
2572 if ( is_wp_error( $charset ) ) {
2576 // We can't reliably strip text from tables containing binary/blob columns
2577 if ( 'binary' === $charset ) {
2581 $charset = $this->charset;
2586 'charset' => $charset,
2590 $data = $this->strip_invalid_text( array( $data ) );
2591 if ( is_wp_error( $data ) ) {
2595 return $data[0]['value'];
2599 * Strips any invalid characters from the string for a given table and column.
2604 * @param string $table Table name.
2605 * @param string $column Column name.
2606 * @param string $value The text to check.
2607 * @return string|WP_Error The converted string, or a `WP_Error` object if the conversion fails.
2609 public function strip_invalid_text_for_column( $table, $column, $value ) {
2610 if ( ! is_string( $value ) || $this->check_ascii( $value ) ) {
2614 $charset = $this->get_col_charset( $table, $column );
2616 // Not a string column.
2618 } elseif ( is_wp_error( $charset ) ) {
2619 // Bail on real errors.
2626 'charset' => $charset,
2631 $data = $this->strip_invalid_text( $data );
2632 if ( is_wp_error( $data ) ) {
2636 return $data[ $column ]['value'];
2640 * Find the first table name referenced in a query.
2645 * @param string $query The query to search.
2646 * @return string|false $table The table name found, or false if a table couldn't be found.
2648 protected function get_table_from_query( $query ) {
2649 // Remove characters that can legally trail the table name.
2650 $query = rtrim( $query, ';/-#' );
2652 // Allow (select...) union [...] style queries. Use the first query's table name.
2653 $query = ltrim( $query, "\r\n\t (" );
2656 * Strip everything between parentheses except nested selects and use only 1,000
2657 * chars of the query.
2659 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $query, 0, 1000 ) );
2661 // Quickly match most common queries.
2662 if ( preg_match( '/^\s*(?:'
2663 . 'SELECT.*?\s+FROM'
2664 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
2665 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
2666 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
2667 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
2668 . ')\s+`?([\w-]+)`?/is', $query, $maybe ) ) {
2672 // SHOW TABLE STATUS and SHOW TABLES
2673 if ( preg_match( '/^\s*(?:'
2674 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2675 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2676 . ')\W([\w-]+)\W/is', $query, $maybe ) ) {
2680 // Big pattern for the rest of the table-related queries.
2681 if ( preg_match( '/^\s*(?:'
2682 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
2683 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
2684 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
2685 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
2686 . '|TRUNCATE(?:\s+TABLE)?'
2687 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
2688 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
2689 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
2690 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
2691 . '|DROP\s+INDEX.*\s+ON'
2692 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
2693 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
2694 . '|SHOW\s+(?:.*FROM|.*TABLE)'
2695 . ')\s+\(*\s*`?([\w-]+)`?\s*\)*/is', $query, $maybe ) ) {
2703 * Load the column metadata from the last query.
2709 protected function load_col_info() {
2710 if ( $this->col_info )
2713 if ( $this->use_mysqli ) {
2714 for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
2715 $this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
2718 for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
2719 $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
2725 * Retrieve column metadata from the last query.
2729 * @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
2730 * @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
2731 * @return mixed Column Results
2733 public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
2734 $this->load_col_info();
2736 if ( $this->col_info ) {
2737 if ( $col_offset == -1 ) {
2739 $new_array = array();
2740 foreach( (array) $this->col_info as $col ) {
2741 $new_array[$i] = $col->{$info_type};
2746 return $this->col_info[$col_offset]->{$info_type};
2752 * Starts the timer, for debugging purposes.
2758 public function timer_start() {
2759 $this->time_start = microtime( true );
2764 * Stops the debugging timer.
2768 * @return float Total time spent on the query, in seconds
2770 public function timer_stop() {
2771 return ( microtime( true ) - $this->time_start );
2775 * Wraps errors in a nice header and footer and dies.
2777 * Will not die if wpdb::$show_errors is false.
2781 * @param string $message The Error message
2782 * @param string $error_code Optional. A Computer readable string to identify the error.
2783 * @return false|void
2785 public function bail( $message, $error_code = '500' ) {
2786 if ( !$this->show_errors ) {
2787 if ( class_exists( 'WP_Error' ) )
2788 $this->error = new WP_Error($error_code, $message);
2790 $this->error = $message;
2797 * Whether MySQL database is at least the required minimum version.
2801 * @uses $required_mysql_version
2805 public function check_database_version() {
2806 global $wp_version, $required_mysql_version;
2807 // Make sure the server has the required MySQL version
2808 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
2809 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
2813 * Whether the database supports collation.
2815 * Called when WordPress is generating the table scheme.
2819 * @deprecated Use wpdb::has_cap( 'collation' )
2821 * @return bool True if collation is supported, false if version does not
2823 public function supports_collation() {
2824 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
2825 return $this->has_cap( 'collation' );
2829 * The database character collate.
2833 * @return string The database character collate.
2835 public function get_charset_collate() {
2836 $charset_collate = '';
2838 if ( ! empty( $this->charset ) )
2839 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
2840 if ( ! empty( $this->collate ) )
2841 $charset_collate .= " COLLATE $this->collate";
2843 return $charset_collate;
2847 * Determine if a database supports a particular feature.
2850 * @since 4.1.0 Support was added for the 'utf8mb4' feature.
2852 * @see wpdb::db_version()
2854 * @param string $db_cap The feature to check for. Accepts 'collation',
2855 * 'group_concat', 'subqueries', 'set_charset',
2857 * @return bool Whether the database feature is supported, false otherwise.
2859 public function has_cap( $db_cap ) {
2860 $version = $this->db_version();
2862 switch ( strtolower( $db_cap ) ) {
2863 case 'collation' : // @since 2.5.0
2864 case 'group_concat' : // @since 2.7.0
2865 case 'subqueries' : // @since 2.7.0
2866 return version_compare( $version, '4.1', '>=' );
2867 case 'set_charset' :
2868 return version_compare( $version, '5.0.7', '>=' );
2869 case 'utf8mb4' : // @since 4.1.0
2870 return version_compare( $version, '5.5.3', '>=' );
2877 * Retrieve the name of the function that called wpdb.
2879 * Searches up the list of functions until it reaches
2880 * the one that would most logically had called this method.
2884 * @return string The name of the calling function
2886 public function get_caller() {
2887 return wp_debug_backtrace_summary( __CLASS__ );
2891 * The database version number.
2895 * @return null|string Null on failure, version number on success.
2897 public function db_version() {
2898 if ( $this->use_mysqli ) {
2899 $server_info = mysqli_get_server_info( $this->dbh );
2901 $server_info = mysql_get_server_info( $this->dbh );
2903 return preg_replace( '/[^0-9.].*/', '', $server_info );