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 * Saved info on the table column
156 * Saved queries that were executed
165 * The number of times to retry reconnecting before dying.
169 * @see wpdb::check_connection()
172 protected $reconnect_retries = 5;
175 * WordPress table prefix
177 * You can set this to have multiple WordPress installations
178 * in a single database. The second reason is for possible
179 * security precautions.
188 * WordPress base table prefix.
197 * Whether the database queries are ready to start executing.
206 * {@internal Missing Description}}
215 * {@internal Missing Description}}
224 * List of WordPress per-blog tables
228 * @see wpdb::tables()
231 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
232 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
235 * List of deprecated WordPress tables
237 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
241 * @see wpdb::tables()
244 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
247 * List of WordPress global tables
251 * @see wpdb::tables()
254 var $global_tables = array( 'users', 'usermeta' );
257 * List of Multisite global tables
261 * @see wpdb::tables()
264 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
265 'sitecategories', 'registration_log', 'blog_versions' );
268 * WordPress Comments table
277 * WordPress Comment Metadata table
286 * WordPress Links table
295 * WordPress Options table
304 * WordPress Post Metadata table
313 * WordPress Posts table
322 * WordPress Terms table
331 * WordPress Term Relationships table
337 public $term_relationships;
340 * WordPress Term Taxonomy table
346 public $term_taxonomy;
349 * Global and Multisite tables
353 * WordPress User Metadata table
362 * WordPress Users table
371 * Multisite Blogs table
380 * Multisite Blog Versions table
386 public $blog_versions;
389 * Multisite Registration Log table
395 public $registration_log;
398 * Multisite Signups table
407 * Multisite Sites table
416 * Multisite Sitewide Terms table
422 public $sitecategories;
425 * Multisite Site Metadata table
434 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
436 * Keys are column names, values are format types: 'ID' => '%d'
439 * @see wpdb::prepare()
440 * @see wpdb::insert()
441 * @see wpdb::update()
442 * @see wpdb::delete()
443 * @see wp_set_wpdb_vars()
447 public $field_types = array();
450 * Database table columns charset
459 * Database table columns collate
483 protected $dbpassword;
513 * A textual description of the last query/get_row/get_var call
522 * Whether MySQL is used as the database engine.
524 * Set in WPDB::db_connect() to true, by default. This is used when checking
525 * against the required MySQL version for WordPress. Normally, a replacement
526 * database drop-in (db.php) will skip these checks, but setting this to true
527 * will force the checks to occur.
533 public $is_mysql = null;
536 * A list of incompatible SQL modes.
542 protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
543 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
546 * Whether to use mysqli over mysql.
552 private $use_mysqli = false;
555 * Whether we've managed to successfully connect at some point
561 private $has_connected = false;
564 * Connects to the database server and selects a database
566 * PHP5 style constructor for compatibility with PHP5. Does
567 * the actual setting up of the class properties and connection
570 * @link https://core.trac.wordpress.org/ticket/3354
573 * @param string $dbuser MySQL database user
574 * @param string $dbpassword MySQL database password
575 * @param string $dbname MySQL database name
576 * @param string $dbhost MySQL database host
578 public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
579 register_shutdown_function( array( $this, '__destruct' ) );
581 if ( WP_DEBUG && WP_DEBUG_DISPLAY )
582 $this->show_errors();
584 /* Use ext/mysqli if it exists and:
585 * - WP_USE_EXT_MYSQL is defined as false, or
586 * - We are a development version of WordPress, or
587 * - We are running PHP 5.5 or greater, or
588 * - ext/mysql is not loaded.
590 if ( function_exists( 'mysqli_connect' ) ) {
591 if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
592 $this->use_mysqli = ! WP_USE_EXT_MYSQL;
593 } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
594 $this->use_mysqli = true;
595 } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
596 $this->use_mysqli = true;
600 $this->init_charset();
602 $this->dbuser = $dbuser;
603 $this->dbpassword = $dbpassword;
604 $this->dbname = $dbname;
605 $this->dbhost = $dbhost;
607 // wp-config.php creation will manually connect when ready.
608 if ( defined( 'WP_SETUP_CONFIG' ) ) {
616 * PHP5 style destructor and will run when database object is destroyed.
618 * @see wpdb::__construct()
622 public function __destruct() {
627 * PHP5 style magic getter, used to lazy-load expensive data.
631 * @param string $name The private member to get, and optionally process
632 * @return mixed The private member
634 public function __get( $name ) {
635 if ( 'col_info' === $name )
636 $this->load_col_info();
642 * Magic function, for backwards compatibility.
646 * @param string $name The private member to set
647 * @param mixed $value The value to set
649 public function __set( $name, $value ) {
650 $this->$name = $value;
654 * Magic function, for backwards compatibility.
658 * @param string $name The private member to check
660 * @return bool If the member is set or not
662 public function __isset( $name ) {
663 return isset( $this->$name );
667 * Magic function, for backwards compatibility.
671 * @param string $name The private member to unset
673 public function __unset( $name ) {
674 unset( $this->$name );
678 * Set $this->charset and $this->collate
682 public function init_charset() {
683 if ( function_exists('is_multisite') && is_multisite() ) {
684 $this->charset = 'utf8';
685 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
686 $this->collate = DB_COLLATE;
688 $this->collate = 'utf8_general_ci';
689 } elseif ( defined( 'DB_COLLATE' ) ) {
690 $this->collate = DB_COLLATE;
693 if ( defined( 'DB_CHARSET' ) )
694 $this->charset = DB_CHARSET;
698 * Sets the connection's character set.
702 * @param resource $dbh The resource given by mysql_connect
703 * @param string $charset Optional. The character set. Default null.
704 * @param string $collate Optional. The collation. Default null.
706 public function set_charset( $dbh, $charset = null, $collate = null ) {
707 if ( ! isset( $charset ) )
708 $charset = $this->charset;
709 if ( ! isset( $collate ) )
710 $collate = $this->collate;
711 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
712 if ( $this->use_mysqli ) {
713 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
714 mysqli_set_charset( $dbh, $charset );
716 $query = $this->prepare( 'SET NAMES %s', $charset );
717 if ( ! empty( $collate ) )
718 $query .= $this->prepare( ' COLLATE %s', $collate );
719 mysqli_query( $query, $dbh );
722 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
723 mysql_set_charset( $charset, $dbh );
725 $query = $this->prepare( 'SET NAMES %s', $charset );
726 if ( ! empty( $collate ) )
727 $query .= $this->prepare( ' COLLATE %s', $collate );
728 mysql_query( $query, $dbh );
735 * Change the current SQL mode, and ensure its WordPress compatibility.
737 * If no modes are passed, it will ensure the current MySQL server
738 * modes are compatible.
742 * @param array $modes Optional. A list of SQL modes to set.
744 public function set_sql_mode( $modes = array() ) {
745 if ( empty( $modes ) ) {
746 if ( $this->use_mysqli ) {
747 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
749 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
752 if ( empty( $res ) ) {
756 if ( $this->use_mysqli ) {
757 $modes_array = mysqli_fetch_array( $res );
758 if ( empty( $modes_array[0] ) ) {
761 $modes_str = $modes_array[0];
763 $modes_str = mysql_result( $res, 0 );
766 if ( empty( $modes_str ) ) {
770 $modes = explode( ',', $modes_str );
773 $modes = array_change_key_case( $modes, CASE_UPPER );
776 * Filter the list of incompatible SQL modes to exclude.
780 * @param array $incompatible_modes An array of incompatible modes.
782 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
784 foreach( $modes as $i => $mode ) {
785 if ( in_array( $mode, $incompatible_modes ) ) {
786 unset( $modes[ $i ] );
790 $modes_str = implode( ',', $modes );
792 if ( $this->use_mysqli ) {
793 mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
795 mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
800 * Sets the table prefix for the WordPress tables.
804 * @param string $prefix Alphanumeric name for the new prefix.
805 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
806 * @return string|WP_Error Old prefix or WP_Error on error
808 public function set_prefix( $prefix, $set_table_names = true ) {
810 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
811 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
813 $old_prefix = is_multisite() ? '' : $prefix;
815 if ( isset( $this->base_prefix ) )
816 $old_prefix = $this->base_prefix;
818 $this->base_prefix = $prefix;
820 if ( $set_table_names ) {
821 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
822 $this->$table = $prefixed_table;
824 if ( is_multisite() && empty( $this->blogid ) )
827 $this->prefix = $this->get_blog_prefix();
829 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
830 $this->$table = $prefixed_table;
832 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
833 $this->$table = $prefixed_table;
843 * @param int $blog_id
844 * @param int $site_id Optional.
845 * @return int previous blog id
847 public function set_blog_id( $blog_id, $site_id = 0 ) {
848 if ( ! empty( $site_id ) )
849 $this->siteid = $site_id;
851 $old_blog_id = $this->blogid;
852 $this->blogid = $blog_id;
854 $this->prefix = $this->get_blog_prefix();
856 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
857 $this->$table = $prefixed_table;
859 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
860 $this->$table = $prefixed_table;
869 * @param int $blog_id Optional.
870 * @return string Blog prefix.
872 public function get_blog_prefix( $blog_id = null ) {
873 if ( is_multisite() ) {
874 if ( null === $blog_id )
875 $blog_id = $this->blogid;
876 $blog_id = (int) $blog_id;
877 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
878 return $this->base_prefix;
880 return $this->base_prefix . $blog_id . '_';
882 return $this->base_prefix;
887 * Returns an array of WordPress tables.
889 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
890 * override the WordPress users and usermeta tables that would otherwise
891 * be determined by the prefix.
893 * The scope argument can take one of the following:
895 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
896 * 'blog' - returns the blog-level tables for the queried blog.
897 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
898 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
899 * 'old' - returns tables which are deprecated.
902 * @uses wpdb::$tables
903 * @uses wpdb::$old_tables
904 * @uses wpdb::$global_tables
905 * @uses wpdb::$ms_global_tables
907 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
908 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
909 * prefix is requested, then the custom users and usermeta tables will be mapped.
910 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
911 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
913 public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
916 $tables = array_merge( $this->global_tables, $this->tables );
917 if ( is_multisite() )
918 $tables = array_merge( $tables, $this->ms_global_tables );
921 $tables = $this->tables;
924 $tables = $this->global_tables;
925 if ( is_multisite() )
926 $tables = array_merge( $tables, $this->ms_global_tables );
929 $tables = $this->ms_global_tables;
932 $tables = $this->old_tables;
940 $blog_id = $this->blogid;
941 $blog_prefix = $this->get_blog_prefix( $blog_id );
942 $base_prefix = $this->base_prefix;
943 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
944 foreach ( $tables as $k => $table ) {
945 if ( in_array( $table, $global_tables ) )
946 $tables[ $table ] = $base_prefix . $table;
948 $tables[ $table ] = $blog_prefix . $table;
949 unset( $tables[ $k ] );
952 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
953 $tables['users'] = CUSTOM_USER_TABLE;
955 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
956 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
963 * Selects a database using the current database connection.
965 * The database name will be changed based on the current database
966 * connection. On failure, the execution will bail and display an DB error.
970 * @param string $db MySQL database name
971 * @param resource $dbh Optional link identifier.
972 * @return null Always null.
974 public function select( $db, $dbh = null ) {
978 if ( $this->use_mysqli ) {
979 $success = @mysqli_select_db( $dbh, $db );
981 $success = @mysql_select_db( $db, $dbh );
984 $this->ready = false;
985 if ( ! did_action( 'template_redirect' ) ) {
986 wp_load_translations_early();
987 $this->bail( sprintf( __( '<h1>Can’t select database</h1>
988 <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>
990 <li>Are you sure it exists?</li>
991 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
992 <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>
994 <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' );
1001 * Do not use, deprecated.
1003 * Use esc_sql() or wpdb::prepare() instead.
1007 * @see wpdb::prepare
1011 * @param string $string
1014 function _weak_escape( $string ) {
1015 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1016 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1017 return addslashes( $string );
1021 * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1023 * @see mysqli_real_escape_string()
1024 * @see mysql_real_escape_string()
1028 * @param string $string to escape
1029 * @return string escaped
1031 function _real_escape( $string ) {
1033 if ( $this->use_mysqli ) {
1034 return mysqli_real_escape_string( $this->dbh, $string );
1036 return mysql_real_escape_string( $string, $this->dbh );
1040 $class = get_class( $this );
1041 if ( function_exists( '__' ) ) {
1042 _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
1044 _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
1046 return addslashes( $string );
1050 * Escape data. Works on arrays.
1052 * @uses wpdb::_real_escape()
1056 * @param string|array $data
1057 * @return string|array escaped
1059 function _escape( $data ) {
1060 if ( is_array( $data ) ) {
1061 foreach ( $data as $k => $v ) {
1063 $data[$k] = $this->_escape( $v );
1065 $data[$k] = $this->_real_escape( $v );
1068 $data = $this->_real_escape( $data );
1075 * Do not use, deprecated.
1077 * Use esc_sql() or wpdb::prepare() instead.
1081 * @see wpdb::prepare()
1084 * @param mixed $data
1087 public function escape( $data ) {
1088 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1089 _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1090 if ( is_array( $data ) ) {
1091 foreach ( $data as $k => $v ) {
1092 if ( is_array( $v ) )
1093 $data[$k] = $this->escape( $v, 'recursive' );
1095 $data[$k] = $this->_weak_escape( $v, 'internal' );
1098 $data = $this->_weak_escape( $data, 'internal' );
1105 * Escapes content by reference for insertion into the database, for security
1107 * @uses wpdb::_real_escape()
1109 * @param string $string to escape
1112 public function escape_by_ref( &$string ) {
1113 if ( ! is_float( $string ) )
1114 $string = $this->_real_escape( $string );
1118 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1120 * The following directives can be used in the query format string:
1124 * %% (literal percentage sign - no argument needed)
1126 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1127 * Literals (%) as parts of the query must be properly written as %%.
1129 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1130 * Does not support sign, padding, alignment, width or precision specifiers.
1131 * Does not support argument numbering/swapping.
1133 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
1135 * Both %d and %s should be left unquoted in the query string.
1137 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1138 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1140 * @link http://php.net/sprintf Description of syntax.
1143 * @param string $query Query statement with sprintf()-like placeholders
1144 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1145 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1146 * being called like {@link http://php.net/sprintf sprintf()}.
1147 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1148 * {@link http://php.net/sprintf sprintf()}.
1149 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
1150 * if there was something to prepare
1152 public function prepare( $query, $args ) {
1153 if ( is_null( $query ) )
1156 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1157 if ( strpos( $query, '%' ) === false ) {
1158 _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
1161 $args = func_get_args();
1162 array_shift( $args );
1163 // If args were passed as an array (as in vsprintf), move them up
1164 if ( isset( $args[0] ) && is_array($args[0]) )
1166 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1167 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1168 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1169 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1170 array_walk( $args, array( $this, 'escape_by_ref' ) );
1171 return @vsprintf( $query, $args );
1175 * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1177 * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1179 * Example Prepared Statement:
1181 * $find = 'only 43% of planets';
1182 * $like = $wild . $wpdb->esc_like( $find ) . $wild;
1183 * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
1185 * Example Escape Chain:
1186 * $sql = esc_sql( $wpdb->esc_like( $input ) );
1191 * @param string $text The raw text to be escaped. The input typed by the user should have no
1192 * extra or deleted slashes.
1193 * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1194 * or real_escape next.
1196 public function esc_like( $text ) {
1197 return addcslashes( $text, '_%\\' );
1201 * Print SQL/DB error.
1204 * @global array $EZSQL_ERROR Stores error information of query and error string
1206 * @param string $str The error to display
1207 * @return false|null False if the showing of errors is disabled.
1209 public function print_error( $str = '' ) {
1210 global $EZSQL_ERROR;
1213 if ( $this->use_mysqli ) {
1214 $str = mysqli_error( $this->dbh );
1216 $str = mysql_error( $this->dbh );
1219 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1221 if ( $this->suppress_errors )
1224 wp_load_translations_early();
1226 if ( $caller = $this->get_caller() )
1227 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1229 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1231 error_log( $error_str );
1233 // Are we showing errors?
1234 if ( ! $this->show_errors )
1237 // If there is an error then take note of it
1238 if ( is_multisite() ) {
1239 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1240 if ( defined( 'ERRORLOGFILE' ) )
1241 error_log( $msg, 3, ERRORLOGFILE );
1242 if ( defined( 'DIEONDBERROR' ) )
1245 $str = htmlspecialchars( $str, ENT_QUOTES );
1246 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1248 print "<div id='error'>
1249 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1250 <code>$query</code></p>
1256 * Enables showing of database errors.
1258 * This function should be used only to enable showing of errors.
1259 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1260 * this function can be used to enable and disable showing of database
1264 * @see wpdb::hide_errors()
1266 * @param bool $show Whether to show or hide errors
1267 * @return bool Old value for showing errors.
1269 public function show_errors( $show = true ) {
1270 $errors = $this->show_errors;
1271 $this->show_errors = $show;
1276 * Disables showing of database errors.
1278 * By default database errors are not shown.
1281 * @see wpdb::show_errors()
1283 * @return bool Whether showing of errors was active
1285 public function hide_errors() {
1286 $show = $this->show_errors;
1287 $this->show_errors = false;
1292 * Whether to suppress database errors.
1294 * By default database errors are suppressed, with a simple
1295 * call to this function they can be enabled.
1298 * @see wpdb::hide_errors()
1299 * @param bool $suppress Optional. New value. Defaults to true.
1300 * @return bool Old value
1302 public function suppress_errors( $suppress = true ) {
1303 $errors = $this->suppress_errors;
1304 $this->suppress_errors = (bool) $suppress;
1309 * Kill cached query results.
1314 public function flush() {
1315 $this->last_result = array();
1316 $this->col_info = null;
1317 $this->last_query = null;
1318 $this->rows_affected = $this->num_rows = 0;
1319 $this->last_error = '';
1321 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1322 mysqli_free_result( $this->result );
1323 $this->result = null;
1325 // Sanity check before using the handle
1326 if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1330 // Clear out any results from a multi-query
1331 while ( mysqli_more_results( $this->dbh ) ) {
1332 mysqli_next_result( $this->dbh );
1334 } else if ( is_resource( $this->result ) ) {
1335 mysql_free_result( $this->result );
1340 * Connect to and select database.
1342 * If $allow_bail is false, the lack of database connection will need
1343 * to be handled manually.
1346 * @since 3.9.0 $allow_bail parameter added.
1348 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1349 * @return null|bool True with a successful connection, false on failure.
1351 public function db_connect( $allow_bail = true ) {
1353 $this->is_mysql = true;
1356 * Deprecated in 3.9+ when using MySQLi. No equivalent
1357 * $new_link parameter exists for mysqli_* functions.
1359 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1360 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1362 if ( $this->use_mysqli ) {
1363 $this->dbh = mysqli_init();
1365 // mysqli_real_connect doesn't support the host param including a port or socket
1366 // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1369 $host = $this->dbhost;
1370 $port_or_socket = strstr( $host, ':' );
1371 if ( ! empty( $port_or_socket ) ) {
1372 $host = substr( $host, 0, strpos( $host, ':' ) );
1373 $port_or_socket = substr( $port_or_socket, 1 );
1374 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1375 $port = intval( $port_or_socket );
1376 $maybe_socket = strstr( $port_or_socket, ':' );
1377 if ( ! empty( $maybe_socket ) ) {
1378 $socket = substr( $maybe_socket, 1 );
1381 $socket = $port_or_socket;
1386 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1388 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1391 if ( $this->dbh->connect_errno ) {
1394 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1395 * - We haven't previously connected, and
1396 * - WP_USE_EXT_MYSQL isn't set to false, and
1397 * - ext/mysql is loaded.
1399 $attempt_fallback = true;
1401 if ( $this->has_connected ) {
1402 $attempt_fallback = false;
1403 } else if ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1404 $attempt_fallback = false;
1405 } else if ( ! function_exists( 'mysql_connect' ) ) {
1406 $attempt_fallback = false;
1409 if ( $attempt_fallback ) {
1410 $this->use_mysqli = false;
1411 $this->db_connect();
1416 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1418 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1422 if ( ! $this->dbh && $allow_bail ) {
1423 wp_load_translations_early();
1425 // Load custom DB error template, if present.
1426 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1427 require_once( WP_CONTENT_DIR . '/db-error.php' );
1431 $this->bail( sprintf( __( "
1432 <h1>Error establishing a database connection</h1>
1433 <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>
1435 <li>Are you sure you have the correct username and password?</li>
1436 <li>Are you sure that you have typed the correct hostname?</li>
1437 <li>Are you sure that the database server is running?</li>
1439 <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>
1440 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1443 } else if ( $this->dbh ) {
1444 $this->has_connected = true;
1445 $this->set_charset( $this->dbh );
1446 $this->set_sql_mode();
1447 $this->ready = true;
1448 $this->select( $this->dbname, $this->dbh );
1457 * Check that the connection to the database is still up. If not, try to reconnect.
1459 * If this function is unable to reconnect, it will forcibly die, or if after the
1460 * the template_redirect hook has been fired, return false instead.
1462 * If $allow_bail is false, the lack of database connection will need
1463 * to be handled manually.
1467 * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1468 * @return bool|null True if the connection is up.
1470 public function check_connection( $allow_bail = true ) {
1471 if ( $this->use_mysqli ) {
1472 if ( @mysqli_ping( $this->dbh ) ) {
1476 if ( @mysql_ping( $this->dbh ) ) {
1481 $error_reporting = false;
1483 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1485 $error_reporting = error_reporting();
1486 error_reporting( $error_reporting & ~E_WARNING );
1489 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1490 // On the last try, re-enable warnings. We want to see a single instance of the
1491 // "unable to connect" message on the bail() screen, if it appears.
1492 if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1493 error_reporting( $error_reporting );
1496 if ( $this->db_connect( false ) ) {
1497 if ( $error_reporting ) {
1498 error_reporting( $error_reporting );
1507 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1508 // Let's just return and hope for the best.
1509 if ( did_action( 'template_redirect' ) ) {
1513 if ( ! $allow_bail ) {
1517 // We weren't able to reconnect, so we better bail.
1518 $this->bail( sprintf( ( "
1519 <h1>Error reconnecting to the database</h1>
1520 <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>
1522 <li>Are you sure that the database server is running?</li>
1523 <li>Are you sure that the database server is not under particularly heavy load?</li>
1525 <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>
1526 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1528 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1533 * Perform a MySQL database query, using current database connection.
1535 * More information can be found on the codex page.
1539 * @param string $query Database query
1540 * @return int|false Number of rows affected/selected or false on error
1542 public function query( $query ) {
1543 if ( ! $this->ready ) {
1548 * Filter the database query.
1550 * Some queries are made before the plugins have been loaded,
1551 * and thus cannot be filtered with this method.
1555 * @param string $query Database query.
1557 $query = apply_filters( 'query', $query );
1561 // Log how the function was called
1562 $this->func_call = "\$db->query(\"$query\")";
1564 // Keep track of the last query for debug..
1565 $this->last_query = $query;
1567 $this->_do_query( $query );
1569 // MySQL server has gone away, try to reconnect
1571 if ( ! empty( $this->dbh ) ) {
1572 if ( $this->use_mysqli ) {
1573 $mysql_errno = mysqli_errno( $this->dbh );
1575 $mysql_errno = mysql_errno( $this->dbh );
1579 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1580 if ( $this->check_connection() ) {
1581 $this->_do_query( $query );
1583 $this->insert_id = 0;
1588 // If there is an error then take note of it..
1589 if ( $this->use_mysqli ) {
1590 $this->last_error = mysqli_error( $this->dbh );
1592 $this->last_error = mysql_error( $this->dbh );
1595 if ( $this->last_error ) {
1596 // Clear insert_id on a subsequent failed insert.
1597 if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1598 $this->insert_id = 0;
1600 $this->print_error();
1604 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1605 $return_val = $this->result;
1606 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1607 if ( $this->use_mysqli ) {
1608 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1610 $this->rows_affected = mysql_affected_rows( $this->dbh );
1612 // Take note of the insert_id
1613 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1614 if ( $this->use_mysqli ) {
1615 $this->insert_id = mysqli_insert_id( $this->dbh );
1617 $this->insert_id = mysql_insert_id( $this->dbh );
1620 // Return number of rows affected
1621 $return_val = $this->rows_affected;
1624 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1625 while ( $row = @mysqli_fetch_object( $this->result ) ) {
1626 $this->last_result[$num_rows] = $row;
1629 } else if ( is_resource( $this->result ) ) {
1630 while ( $row = @mysql_fetch_object( $this->result ) ) {
1631 $this->last_result[$num_rows] = $row;
1636 // Log number of rows the query returned
1637 // and return number of rows selected
1638 $this->num_rows = $num_rows;
1639 $return_val = $num_rows;
1646 * Internal function to perform the mysql_query() call.
1651 * @see wpdb::query()
1653 * @param string $query The query to run.
1655 private function _do_query( $query ) {
1656 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1657 $this->timer_start();
1660 if ( $this->use_mysqli ) {
1661 $this->result = @mysqli_query( $this->dbh, $query );
1663 $this->result = @mysql_query( $query, $this->dbh );
1665 $this->num_queries++;
1667 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1668 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1673 * Insert a row into a table.
1675 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1676 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1679 * @see wpdb::prepare()
1680 * @see wpdb::$field_types
1681 * @see wp_set_wpdb_vars()
1683 * @param string $table table name
1684 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1685 * @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.
1686 * 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.
1687 * @return int|false The number of rows inserted, or false on error.
1689 public function insert( $table, $data, $format = null ) {
1690 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1694 * Replace a row into a table.
1696 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1697 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1700 * @see wpdb::prepare()
1701 * @see wpdb::$field_types
1702 * @see wp_set_wpdb_vars()
1704 * @param string $table table name
1705 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1706 * @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.
1707 * 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.
1708 * @return int|false The number of rows affected, or false on error.
1710 public function replace( $table, $data, $format = null ) {
1711 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1715 * Helper function for insert and replace.
1717 * Runs an insert or replace query based on $type argument.
1721 * @see wpdb::prepare()
1722 * @see wpdb::$field_types
1723 * @see wp_set_wpdb_vars()
1725 * @param string $table table name
1726 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1727 * @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.
1728 * 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.
1729 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1730 * @return int|false The number of rows affected, or false on error.
1732 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1733 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1735 $this->insert_id = 0;
1736 $formats = $format = (array) $format;
1737 $fields = array_keys( $data );
1738 $formatted_fields = array();
1739 foreach ( $fields as $field ) {
1740 if ( !empty( $format ) )
1741 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1742 elseif ( isset( $this->field_types[$field] ) )
1743 $form = $this->field_types[$field];
1746 $formatted_fields[] = $form;
1748 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
1749 return $this->query( $this->prepare( $sql, $data ) );
1753 * Update a row in the table
1755 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1756 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%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 update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1765 * @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".
1766 * @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.
1767 * 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.
1768 * @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.
1769 * @return int|false The number of rows updated, or false on error.
1771 public function update( $table, $data, $where, $format = null, $where_format = null ) {
1772 if ( ! is_array( $data ) || ! is_array( $where ) )
1775 $formats = $format = (array) $format;
1776 $bits = $wheres = array();
1777 foreach ( (array) array_keys( $data ) as $field ) {
1778 if ( !empty( $format ) )
1779 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1780 elseif ( isset($this->field_types[$field]) )
1781 $form = $this->field_types[$field];
1784 $bits[] = "`$field` = {$form}";
1787 $where_formats = $where_format = (array) $where_format;
1788 foreach ( (array) array_keys( $where ) as $field ) {
1789 if ( !empty( $where_format ) )
1790 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1791 elseif ( isset( $this->field_types[$field] ) )
1792 $form = $this->field_types[$field];
1795 $wheres[] = "`$field` = {$form}";
1798 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1799 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1803 * Delete a row in the table
1805 * wpdb::delete( 'table', array( 'ID' => 1 ) )
1806 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1809 * @see wpdb::prepare()
1810 * @see wpdb::$field_types
1811 * @see wp_set_wpdb_vars()
1813 * @param string $table table name
1814 * @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".
1815 * @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.
1816 * @return int|false The number of rows updated, or false on error.
1818 public function delete( $table, $where, $where_format = null ) {
1819 if ( ! is_array( $where ) )
1824 $where_formats = $where_format = (array) $where_format;
1826 foreach ( array_keys( $where ) as $field ) {
1827 if ( !empty( $where_format ) ) {
1828 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1829 } elseif ( isset( $this->field_types[ $field ] ) ) {
1830 $form = $this->field_types[ $field ];
1835 $wheres[] = "$field = $form";
1838 $sql = "DELETE FROM $table WHERE " . implode( ' AND ', $wheres );
1839 return $this->query( $this->prepare( $sql, $where ) );
1843 * Retrieve one variable from the database.
1845 * Executes a SQL query and returns the value from the SQL result.
1846 * 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.
1847 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1851 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1852 * @param int $x Optional. Column of value to return. Indexed from 0.
1853 * @param int $y Optional. Row of value to return. Indexed from 0.
1854 * @return string|null Database query result (as string), or null on failure
1856 public function get_var( $query = null, $x = 0, $y = 0 ) {
1857 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1860 $this->query( $query );
1863 // Extract var out of cached results based x,y vals
1864 if ( !empty( $this->last_result[$y] ) ) {
1865 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1868 // If there is a value return it else return null
1869 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1873 * Retrieve one row from the database.
1875 * Executes a SQL query and returns the row from the SQL result.
1879 * @param string|null $query SQL query.
1880 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1881 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1882 * @param int $y Optional. Row to return. Indexed from 0.
1883 * @return mixed Database query result in format specified by $output or null on failure
1885 public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1886 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1888 $this->query( $query );
1893 if ( !isset( $this->last_result[$y] ) )
1896 if ( $output == OBJECT ) {
1897 return $this->last_result[$y] ? $this->last_result[$y] : null;
1898 } elseif ( $output == ARRAY_A ) {
1899 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1900 } elseif ( $output == ARRAY_N ) {
1901 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1902 } elseif ( strtoupper( $output ) === OBJECT ) {
1903 // Back compat for OBJECT being previously case insensitive.
1904 return $this->last_result[$y] ? $this->last_result[$y] : null;
1906 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
1911 * Retrieve one column from the database.
1913 * Executes a SQL query and returns the column from the SQL result.
1914 * If the SQL result contains more than one column, this function returns the column specified.
1915 * If $query is null, this function returns the specified column from the previous SQL result.
1919 * @param string|null $query Optional. SQL query. Defaults to previous query.
1920 * @param int $x Optional. Column to return. Indexed from 0.
1921 * @return array Database query result. Array indexed from 0 by SQL result row number.
1923 public function get_col( $query = null , $x = 0 ) {
1925 $this->query( $query );
1928 $new_array = array();
1929 // Extract the column values
1930 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1931 $new_array[$i] = $this->get_var( null, $x, $i );
1937 * Retrieve an entire SQL result set from the database (i.e., many rows)
1939 * Executes a SQL query and returns the entire SQL result.
1943 * @param string $query SQL query.
1944 * @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.
1945 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1946 * 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.
1947 * @return mixed Database query results
1949 public function get_results( $query = null, $output = OBJECT ) {
1950 $this->func_call = "\$db->get_results(\"$query\", $output)";
1953 $this->query( $query );
1958 $new_array = array();
1959 if ( $output == OBJECT ) {
1960 // Return an integer-keyed array of row objects
1961 return $this->last_result;
1962 } elseif ( $output == OBJECT_K ) {
1963 // Return an array of row objects with keys from column 1
1964 // (Duplicates are discarded)
1965 foreach ( $this->last_result as $row ) {
1966 $var_by_ref = get_object_vars( $row );
1967 $key = array_shift( $var_by_ref );
1968 if ( ! isset( $new_array[ $key ] ) )
1969 $new_array[ $key ] = $row;
1972 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1973 // Return an integer-keyed array of...
1974 if ( $this->last_result ) {
1975 foreach( (array) $this->last_result as $row ) {
1976 if ( $output == ARRAY_N ) {
1977 // ...integer-keyed row arrays
1978 $new_array[] = array_values( get_object_vars( $row ) );
1980 // ...column name-keyed row arrays
1981 $new_array[] = get_object_vars( $row );
1986 } elseif ( strtoupper( $output ) === OBJECT ) {
1987 // Back compat for OBJECT being previously case insensitive.
1988 return $this->last_result;
1994 * Load the column metadata from the last query.
2000 protected function load_col_info() {
2001 if ( $this->col_info )
2004 if ( $this->use_mysqli ) {
2005 for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
2006 $this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
2009 for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
2010 $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
2016 * Retrieve column metadata from the last query.
2020 * @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
2021 * @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
2022 * @return mixed Column Results
2024 public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
2025 $this->load_col_info();
2027 if ( $this->col_info ) {
2028 if ( $col_offset == -1 ) {
2030 $new_array = array();
2031 foreach( (array) $this->col_info as $col ) {
2032 $new_array[$i] = $col->{$info_type};
2037 return $this->col_info[$col_offset]->{$info_type};
2043 * Starts the timer, for debugging purposes.
2049 public function timer_start() {
2050 $this->time_start = microtime( true );
2055 * Stops the debugging timer.
2059 * @return float Total time spent on the query, in seconds
2061 public function timer_stop() {
2062 return ( microtime( true ) - $this->time_start );
2066 * Wraps errors in a nice header and footer and dies.
2068 * Will not die if wpdb::$show_errors is false.
2072 * @param string $message The Error message
2073 * @param string $error_code Optional. A Computer readable string to identify the error.
2074 * @return false|void
2076 public function bail( $message, $error_code = '500' ) {
2077 if ( !$this->show_errors ) {
2078 if ( class_exists( 'WP_Error' ) )
2079 $this->error = new WP_Error($error_code, $message);
2081 $this->error = $message;
2088 * Whether MySQL database is at least the required minimum version.
2092 * @uses $required_mysql_version
2096 public function check_database_version() {
2097 global $wp_version, $required_mysql_version;
2098 // Make sure the server has the required MySQL version
2099 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
2100 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
2104 * Whether the database supports collation.
2106 * Called when WordPress is generating the table scheme.
2110 * @deprecated Use wpdb::has_cap( 'collation' )
2112 * @return bool True if collation is supported, false if version does not
2114 public function supports_collation() {
2115 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
2116 return $this->has_cap( 'collation' );
2120 * The database character collate.
2124 * @return string The database character collate.
2126 public function get_charset_collate() {
2127 $charset_collate = '';
2129 if ( ! empty( $this->charset ) )
2130 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
2131 if ( ! empty( $this->collate ) )
2132 $charset_collate .= " COLLATE $this->collate";
2134 return $charset_collate;
2138 * Determine if a database supports a particular feature.
2141 * @since 4.1.0 Support was added for the 'utf8mb4' feature.
2143 * @see wpdb::db_version()
2145 * @param string $db_cap The feature to check for. Accepts 'collation',
2146 * 'group_concat', 'subqueries', 'set_charset',
2148 * @return bool Whether the database feature is supported, false otherwise.
2150 public function has_cap( $db_cap ) {
2151 $version = $this->db_version();
2153 switch ( strtolower( $db_cap ) ) {
2154 case 'collation' : // @since 2.5.0
2155 case 'group_concat' : // @since 2.7.0
2156 case 'subqueries' : // @since 2.7.0
2157 return version_compare( $version, '4.1', '>=' );
2158 case 'set_charset' :
2159 return version_compare( $version, '5.0.7', '>=' );
2160 case 'utf8mb4' : // @since 4.1.0
2161 return version_compare( $version, '5.5.3', '>=' );
2168 * Retrieve the name of the function that called wpdb.
2170 * Searches up the list of functions until it reaches
2171 * the one that would most logically had called this method.
2175 * @return string The name of the calling function
2177 public function get_caller() {
2178 return wp_debug_backtrace_summary( __CLASS__ );
2182 * The database version number.
2186 * @return null|string Null on failure, version number on success.
2188 public function db_version() {
2189 if ( $this->use_mysqli ) {
2190 $server_info = mysqli_get_server_info( $this->dbh );
2192 $server_info = mysql_get_server_info( $this->dbh );
2194 return preg_replace( '/[^0-9.].*/', '', $server_info );