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 http://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 The character set (optional)
704
* @param string $collate The collation (optional)
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
* @see wpdb::$incompatible_modes
782
* @param array $incompatible_modes An array of incompatible modes.
784
$incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
786
foreach( $modes as $i => $mode ) {
787
if ( in_array( $mode, $incompatible_modes ) ) {
788
unset( $modes[ $i ] );
792
$modes_str = implode( ',', $modes );
794
if ( $this->use_mysqli ) {
795
mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
797
mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
802
* Sets the table prefix for the WordPress tables.
806
* @param string $prefix Alphanumeric name for the new prefix.
807
* @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
808
* @return string|WP_Error Old prefix or WP_Error on error
810
public function set_prefix( $prefix, $set_table_names = true ) {
812
if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
813
return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
815
$old_prefix = is_multisite() ? '' : $prefix;
817
if ( isset( $this->base_prefix ) )
818
$old_prefix = $this->base_prefix;
820
$this->base_prefix = $prefix;
822
if ( $set_table_names ) {
823
foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
824
$this->$table = $prefixed_table;
826
if ( is_multisite() && empty( $this->blogid ) )
829
$this->prefix = $this->get_blog_prefix();
831
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
832
$this->$table = $prefixed_table;
834
foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
835
$this->$table = $prefixed_table;
845
* @param int $blog_id
846
* @param int $site_id Optional.
847
* @return string previous blog id
849
public function set_blog_id( $blog_id, $site_id = 0 ) {
850
if ( ! empty( $site_id ) )
851
$this->siteid = $site_id;
853
$old_blog_id = $this->blogid;
854
$this->blogid = $blog_id;
856
$this->prefix = $this->get_blog_prefix();
858
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
859
$this->$table = $prefixed_table;
861
foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
862
$this->$table = $prefixed_table;
870
* @uses is_multisite()
872
* @param int $blog_id Optional.
873
* @return string Blog prefix.
875
public function get_blog_prefix( $blog_id = null ) {
876
if ( is_multisite() ) {
877
if ( null === $blog_id )
878
$blog_id = $this->blogid;
879
$blog_id = (int) $blog_id;
880
if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
881
return $this->base_prefix;
883
return $this->base_prefix . $blog_id . '_';
885
return $this->base_prefix;
890
* Returns an array of WordPress tables.
892
* Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
893
* override the WordPress users and usermeta tables that would otherwise
894
* be determined by the prefix.
896
* The scope argument can take one of the following:
898
* 'all' - returns 'all' and 'global' tables. No old tables are returned.
899
* 'blog' - returns the blog-level tables for the queried blog.
900
* 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
901
* 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
902
* 'old' - returns tables which are deprecated.
905
* @uses wpdb::$tables
906
* @uses wpdb::$old_tables
907
* @uses wpdb::$global_tables
908
* @uses wpdb::$ms_global_tables
909
* @uses is_multisite()
911
* @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
912
* @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
913
* prefix is requested, then the custom users and usermeta tables will be mapped.
914
* @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
915
* @return array Table names. When a prefix is requested, the key is the unprefixed table name.
917
public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
920
$tables = array_merge( $this->global_tables, $this->tables );
921
if ( is_multisite() )
922
$tables = array_merge( $tables, $this->ms_global_tables );
925
$tables = $this->tables;
928
$tables = $this->global_tables;
929
if ( is_multisite() )
930
$tables = array_merge( $tables, $this->ms_global_tables );
933
$tables = $this->ms_global_tables;
936
$tables = $this->old_tables;
944
$blog_id = $this->blogid;
945
$blog_prefix = $this->get_blog_prefix( $blog_id );
946
$base_prefix = $this->base_prefix;
947
$global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
948
foreach ( $tables as $k => $table ) {
949
if ( in_array( $table, $global_tables ) )
950
$tables[ $table ] = $base_prefix . $table;
952
$tables[ $table ] = $blog_prefix . $table;
953
unset( $tables[ $k ] );
956
if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
957
$tables['users'] = CUSTOM_USER_TABLE;
959
if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
960
$tables['usermeta'] = CUSTOM_USER_META_TABLE;
967
* Selects a database using the current database connection.
969
* The database name will be changed based on the current database
970
* connection. On failure, the execution will bail and display an DB error.
974
* @param string $db MySQL database name
975
* @param resource $dbh Optional link identifier.
976
* @return null Always null.
978
public function select( $db, $dbh = null ) {
982
if ( $this->use_mysqli ) {
983
$success = @mysqli_select_db( $dbh, $db );
985
$success = @mysql_select_db( $db, $dbh );
988
$this->ready = false;
989
if ( ! did_action( 'template_redirect' ) ) {
990
wp_load_translations_early();
991
$this->bail( sprintf( __( '<h1>Can’t select database</h1>
992
<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>
994
<li>Are you sure it exists?</li>
995
<li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
996
<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>
998
<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' );
1005
* Do not use, deprecated.
1007
* Use esc_sql() or wpdb::prepare() instead.
1011
* @see wpdb::prepare
1015
* @param string $string
1018
function _weak_escape( $string ) {
1019
if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1020
_deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
1021
return addslashes( $string );
1025
* Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1027
* @see mysqli_real_escape_string()
1028
* @see mysql_real_escape_string()
1032
* @param string $string to escape
1033
* @return string escaped
1035
function _real_escape( $string ) {
1037
if ( $this->use_mysqli ) {
1038
return mysqli_real_escape_string( $this->dbh, $string );
1040
return mysql_real_escape_string( $string, $this->dbh );
1044
$class = get_class( $this );
1045
_doing_it_wrong( $class, "$class must set a database connection for use with escaping.", 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.
1138
* wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1139
* wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1142
* @link http://php.net/sprintf Description of syntax.
1145
* @param string $query Query statement with sprintf()-like placeholders
1146
* @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
1147
* {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1148
* being called like {@link http://php.net/sprintf sprintf()}.
1149
* @param mixed $args,... further variables to substitute into the query's placeholders if being called like
1150
* {@link http://php.net/sprintf sprintf()}.
1151
* @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
1152
* if there was something to prepare
1154
public function prepare( $query, $args ) {
1155
if ( is_null( $query ) )
1158
// This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1159
if ( strpos( $query, '%' ) === false ) {
1160
_doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
1163
$args = func_get_args();
1164
array_shift( $args );
1165
// If args were passed as an array (as in vsprintf), move them up
1166
if ( isset( $args[0] ) && is_array($args[0]) )
1168
$query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1169
$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1170
$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1171
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1172
array_walk( $args, array( $this, 'escape_by_ref' ) );
1173
return @vsprintf( $query, $args );
1177
* First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1179
* Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
1181
* Example Prepared Statement:
1183
* $find = 'only 43% of planets';
1184
* $like = $wild . $wpdb->esc_like( $find ) . $wild;
1185
* $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
1187
* Example Escape Chain:
1188
* $sql = esc_sql( $wpdb->esc_like( $input ) );
1193
* @param string $text The raw text to be escaped. The input typed by the user should have no
1194
* extra or deleted slashes.
1195
* @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1196
* or real_escape next.
1198
public function esc_like( $text ) {
1199
return addcslashes( $text, '_%\\' );
1203
* Print SQL/DB error.
1206
* @global array $EZSQL_ERROR Stores error information of query and error string
1208
* @param string $str The error to display
1209
* @return bool False if the showing of errors is disabled.
1211
public function print_error( $str = '' ) {
1212
global $EZSQL_ERROR;
1215
if ( $this->use_mysqli ) {
1216
$str = mysqli_error( $this->dbh );
1218
$str = mysql_error( $this->dbh );
1221
$EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1223
if ( $this->suppress_errors )
1226
wp_load_translations_early();
1228
if ( $caller = $this->get_caller() )
1229
$error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1231
$error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1233
error_log( $error_str );
1235
// Are we showing errors?
1236
if ( ! $this->show_errors )
1239
// If there is an error then take note of it
1240
if ( is_multisite() ) {
1241
$msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1242
if ( defined( 'ERRORLOGFILE' ) )
1243
error_log( $msg, 3, ERRORLOGFILE );
1244
if ( defined( 'DIEONDBERROR' ) )
1247
$str = htmlspecialchars( $str, ENT_QUOTES );
1248
$query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1250
print "<div id='error'>
1251
<p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1252
<code>$query</code></p>
1258
* Enables showing of database errors.
1260
* This function should be used only to enable showing of errors.
1261
* wpdb::hide_errors() should be used instead for hiding of errors. However,
1262
* this function can be used to enable and disable showing of database
1266
* @see wpdb::hide_errors()
1268
* @param bool $show Whether to show or hide errors
1269
* @return bool Old value for showing errors.
1271
public function show_errors( $show = true ) {
1272
$errors = $this->show_errors;
1273
$this->show_errors = $show;
1278
* Disables showing of database errors.
1280
* By default database errors are not shown.
1283
* @see wpdb::show_errors()
1285
* @return bool Whether showing of errors was active
1287
public function hide_errors() {
1288
$show = $this->show_errors;
1289
$this->show_errors = false;
1294
* Whether to suppress database errors.
1296
* By default database errors are suppressed, with a simple
1297
* call to this function they can be enabled.
1300
* @see wpdb::hide_errors()
1301
* @param bool $suppress Optional. New value. Defaults to true.
1302
* @return bool Old value
1304
public function suppress_errors( $suppress = true ) {
1305
$errors = $this->suppress_errors;
1306
$this->suppress_errors = (bool) $suppress;
1311
* Kill cached query results.
1316
public function flush() {
1317
$this->last_result = array();
1318
$this->col_info = null;
1319
$this->last_query = null;
1320
$this->rows_affected = $this->num_rows = 0;
1321
$this->last_error = '';
1323
if ( is_resource( $this->result ) ) {
1324
if ( $this->use_mysqli ) {
1325
mysqli_free_result( $this->result );
1327
mysql_free_result( $this->result );
1333
* Connect to and select database.
1335
* If $allow_bail is false, the lack of database connection will need
1336
* to be handled manually.
1339
* @since 3.9.0 $allow_bail parameter added.
1341
* @param bool $allow_bail Optional. Allows the function to bail. Default true.
1342
* @return bool True with a successful connection, false on failure.
1344
public function db_connect( $allow_bail = true ) {
1346
$this->is_mysql = true;
1349
* Deprecated in 3.9+ when using MySQLi. No equivalent
1350
* $new_link parameter exists for mysqli_* functions.
1352
$new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1353
$client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1355
if ( $this->use_mysqli ) {
1356
$this->dbh = mysqli_init();
1358
// mysqli_real_connect doesn't support the host param including a port or socket
1359
// like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1362
$host = $this->dbhost;
1363
$port_or_socket = strstr( $host, ':' );
1364
if ( ! empty( $port_or_socket ) ) {
1365
$host = substr( $host, 0, strpos( $host, ':' ) );
1366
$port_or_socket = substr( $port_or_socket, 1 );
1367
if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1368
$port = intval( $port_or_socket );
1369
$maybe_socket = strstr( $port_or_socket, ':' );
1370
if ( ! empty( $maybe_socket ) ) {
1371
$socket = substr( $maybe_socket, 1 );
1374
$socket = $port_or_socket;
1379
mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1381
@mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1384
if ( $this->dbh->connect_errno ) {
1387
/* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1388
* - We haven't previously connected, and
1389
* - WP_USE_EXT_MYSQL isn't set to false, and
1390
* - ext/mysql is loaded.
1392
$attempt_fallback = true;
1394
if ( $this->has_connected ) {
1395
$attempt_fallback = false;
1396
} else if ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1397
$attempt_fallback = false;
1398
} else if ( ! function_exists( 'mysql_connect' ) ) {
1399
$attempt_fallback = false;
1402
if ( $attempt_fallback ) {
1403
$this->use_mysqli = false;
1404
$this->db_connect();
1409
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1411
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1415
if ( ! $this->dbh && $allow_bail ) {
1416
wp_load_translations_early();
1418
// Load custom DB error template, if present.
1419
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1420
require_once( WP_CONTENT_DIR . '/db-error.php' );
1424
$this->bail( sprintf( __( "
1425
<h1>Error establishing a database connection</h1>
1426
<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>
1428
<li>Are you sure you have the correct username and password?</li>
1429
<li>Are you sure that you have typed the correct hostname?</li>
1430
<li>Are you sure that the database server is running?</li>
1432
<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>
1433
" ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1436
} else if ( $this->dbh ) {
1437
$this->has_connected = true;
1438
$this->set_charset( $this->dbh );
1439
$this->set_sql_mode();
1440
$this->ready = true;
1441
$this->select( $this->dbname, $this->dbh );
1450
* Check that the connection to the database is still up. If not, try to reconnect.
1452
* If this function is unable to reconnect, it will forcibly die, or if after the
1453
* the template_redirect hook has been fired, return false instead.
1455
* If $allow_bail is false, the lack of database connection will need
1456
* to be handled manually.
1460
* @param bool $allow_bail Optional. Allows the function to bail. Default true.
1461
* @return bool True if the connection is up.
1463
public function check_connection( $allow_bail = true ) {
1464
if ( $this->use_mysqli ) {
1465
if ( @mysqli_ping( $this->dbh ) ) {
1469
if ( @mysql_ping( $this->dbh ) ) {
1474
$error_reporting = false;
1476
// Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1478
$error_reporting = error_reporting();
1479
error_reporting( $error_reporting & ~E_WARNING );
1482
for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1483
// On the last try, re-enable warnings. We want to see a single instance of the
1484
// "unable to connect" message on the bail() screen, if it appears.
1485
if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1486
error_reporting( $error_reporting );
1489
if ( $this->db_connect( false ) ) {
1490
if ( $error_reporting ) {
1491
error_reporting( $error_reporting );
1500
// If template_redirect has already happened, it's too late for wp_die()/dead_db().
1501
// Let's just return and hope for the best.
1502
if ( did_action( 'template_redirect' ) ) {
1506
if ( ! $allow_bail ) {
1510
// We weren't able to reconnect, so we better bail.
1511
$this->bail( sprintf( ( "
1512
<h1>Error reconnecting to the database</h1>
1513
<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>
1515
<li>Are you sure that the database server is running?</li>
1516
<li>Are you sure that the database server is not under particularly heavy load?</li>
1518
<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>
1519
" ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1521
// Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1526
* Perform a MySQL database query, using current database connection.
1528
* More information can be found on the codex page.
1532
* @param string $query Database query
1533
* @return int|false Number of rows affected/selected or false on error
1535
public function query( $query ) {
1536
if ( ! $this->ready )
1540
* Filter the database query.
1542
* Some queries are made before the plugins have been loaded,
1543
* and thus cannot be filtered with this method.
1547
* @param string $query Database query.
1549
$query = apply_filters( 'query', $query );
1553
// Log how the function was called
1554
$this->func_call = "\$db->query(\"$query\")";
1556
// Keep track of the last query for debug..
1557
$this->last_query = $query;
1559
$this->_do_query( $query );
1561
// MySQL server has gone away, try to reconnect
1563
if ( ! empty( $this->dbh ) ) {
1564
if ( $this->use_mysqli ) {
1565
$mysql_errno = mysqli_errno( $this->dbh );
1567
$mysql_errno = mysql_errno( $this->dbh );
1571
if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1572
if ( $this->check_connection() ) {
1573
$this->_do_query( $query );
1575
$this->insert_id = 0;
1580
// If there is an error then take note of it..
1581
if ( $this->use_mysqli ) {
1582
$this->last_error = mysqli_error( $this->dbh );
1584
$this->last_error = mysql_error( $this->dbh );
1587
if ( $this->last_error ) {
1588
// Clear insert_id on a subsequent failed insert.
1589
if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1590
$this->insert_id = 0;
1592
$this->print_error();
1596
if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1597
$return_val = $this->result;
1598
} elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1599
if ( $this->use_mysqli ) {
1600
$this->rows_affected = mysqli_affected_rows( $this->dbh );
1602
$this->rows_affected = mysql_affected_rows( $this->dbh );
1604
// Take note of the insert_id
1605
if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1606
if ( $this->use_mysqli ) {
1607
$this->insert_id = mysqli_insert_id( $this->dbh );
1609
$this->insert_id = mysql_insert_id( $this->dbh );
1612
// Return number of rows affected
1613
$return_val = $this->rows_affected;
1616
if ( $this->use_mysqli ) {
1617
while ( $row = @mysqli_fetch_object( $this->result ) ) {
1618
$this->last_result[$num_rows] = $row;
1622
while ( $row = @mysql_fetch_object( $this->result ) ) {
1623
$this->last_result[$num_rows] = $row;
1628
// Log number of rows the query returned
1629
// and return number of rows selected
1630
$this->num_rows = $num_rows;
1631
$return_val = $num_rows;
1638
* Internal function to perform the mysql_query() call.
1643
* @see wpdb::query()
1645
* @param string $query The query to run.
1647
private function _do_query( $query ) {
1648
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1649
$this->timer_start();
1652
if ( $this->use_mysqli ) {
1653
$this->result = @mysqli_query( $this->dbh, $query );
1655
$this->result = @mysql_query( $query, $this->dbh );
1657
$this->num_queries++;
1659
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1660
$this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1665
* Insert a row into a table.
1668
* wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1669
* wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1673
* @see wpdb::prepare()
1674
* @see wpdb::$field_types
1675
* @see wp_set_wpdb_vars()
1677
* @param string $table table name
1678
* @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1679
* @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.
1680
* 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.
1681
* @return int|false The number of rows inserted, or false on error.
1683
public function insert( $table, $data, $format = null ) {
1684
return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1688
* Replace a row into a table.
1691
* wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1692
* wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1696
* @see wpdb::prepare()
1697
* @see wpdb::$field_types
1698
* @see wp_set_wpdb_vars()
1700
* @param string $table table name
1701
* @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1702
* @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.
1703
* 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.
1704
* @return int|false The number of rows affected, or false on error.
1706
public function replace( $table, $data, $format = null ) {
1707
return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1711
* Helper function for insert and replace.
1713
* Runs an insert or replace query based on $type argument.
1717
* @see wpdb::prepare()
1718
* @see wpdb::$field_types
1719
* @see wp_set_wpdb_vars()
1721
* @param string $table table name
1722
* @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1723
* @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.
1724
* 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.
1725
* @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1726
* @return int|false The number of rows affected, or false on error.
1728
function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1729
if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1731
$this->insert_id = 0;
1732
$formats = $format = (array) $format;
1733
$fields = array_keys( $data );
1734
$formatted_fields = array();
1735
foreach ( $fields as $field ) {
1736
if ( !empty( $format ) )
1737
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1738
elseif ( isset( $this->field_types[$field] ) )
1739
$form = $this->field_types[$field];
1742
$formatted_fields[] = $form;
1744
$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
1745
return $this->query( $this->prepare( $sql, $data ) );
1749
* Update a row in the table
1752
* wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1753
* wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1757
* @see wpdb::prepare()
1758
* @see wpdb::$field_types
1759
* @see wp_set_wpdb_vars()
1761
* @param string $table table name
1762
* @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1763
* @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".
1764
* @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.
1765
* A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1766
* @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.
1767
* @return int|false The number of rows updated, or false on error.
1769
public function update( $table, $data, $where, $format = null, $where_format = null ) {
1770
if ( ! is_array( $data ) || ! is_array( $where ) )
1773
$formats = $format = (array) $format;
1774
$bits = $wheres = array();
1775
foreach ( (array) array_keys( $data ) as $field ) {
1776
if ( !empty( $format ) )
1777
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1778
elseif ( isset($this->field_types[$field]) )
1779
$form = $this->field_types[$field];
1782
$bits[] = "`$field` = {$form}";
1785
$where_formats = $where_format = (array) $where_format;
1786
foreach ( (array) array_keys( $where ) as $field ) {
1787
if ( !empty( $where_format ) )
1788
$form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1789
elseif ( isset( $this->field_types[$field] ) )
1790
$form = $this->field_types[$field];
1793
$wheres[] = "`$field` = {$form}";
1796
$sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1797
return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1801
* Delete a row in the table
1804
* wpdb::delete( 'table', array( 'ID' => 1 ) )
1805
* 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 ) );
1844
* Retrieve one variable from the database.
1846
* Executes a SQL query and returns the value from the SQL result.
1847
* 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.
1848
* If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1852
* @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1853
* @param int $x Optional. Column of value to return. Indexed from 0.
1854
* @param int $y Optional. Row of value to return. Indexed from 0.
1855
* @return string|null Database query result (as string), or null on failure
1857
public function get_var( $query = null, $x = 0, $y = 0 ) {
1858
$this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1860
$this->query( $query );
1862
// Extract var out of cached results based x,y vals
1863
if ( !empty( $this->last_result[$y] ) ) {
1864
$values = array_values( get_object_vars( $this->last_result[$y] ) );
1867
// If there is a value return it else return null
1868
return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1872
* Retrieve one row from the database.
1874
* Executes a SQL query and returns the row from the SQL result.
1878
* @param string|null $query SQL query.
1879
* @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1880
* a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1881
* @param int $y Optional. Row to return. Indexed from 0.
1882
* @return mixed Database query result in format specified by $output or null on failure
1884
public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1885
$this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1887
$this->query( $query );
1891
if ( !isset( $this->last_result[$y] ) )
1894
if ( $output == OBJECT ) {
1895
return $this->last_result[$y] ? $this->last_result[$y] : null;
1896
} elseif ( $output == ARRAY_A ) {
1897
return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1898
} elseif ( $output == ARRAY_N ) {
1899
return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1900
} elseif ( strtoupper( $output ) === OBJECT ) {
1901
// Back compat for OBJECT being previously case insensitive.
1902
return $this->last_result[$y] ? $this->last_result[$y] : null;
1904
$this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
1909
* Retrieve one column from the database.
1911
* Executes a SQL query and returns the column from the SQL result.
1912
* If the SQL result contains more than one column, this function returns the column specified.
1913
* If $query is null, this function returns the specified column from the previous SQL result.
1917
* @param string|null $query Optional. SQL query. Defaults to previous query.
1918
* @param int $x Optional. Column to return. Indexed from 0.
1919
* @return array Database query result. Array indexed from 0 by SQL result row number.
1921
public function get_col( $query = null , $x = 0 ) {
1923
$this->query( $query );
1925
$new_array = array();
1926
// Extract the column values
1927
for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1928
$new_array[$i] = $this->get_var( null, $x, $i );
1934
* Retrieve an entire SQL result set from the database (i.e., many rows)
1936
* Executes a SQL query and returns the entire SQL result.
1940
* @param string $query SQL query.
1941
* @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.
1942
* Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1943
* 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.
1944
* @return mixed Database query results
1946
public function get_results( $query = null, $output = OBJECT ) {
1947
$this->func_call = "\$db->get_results(\"$query\", $output)";
1950
$this->query( $query );
1954
$new_array = array();
1955
if ( $output == OBJECT ) {
1956
// Return an integer-keyed array of row objects
1957
return $this->last_result;
1958
} elseif ( $output == OBJECT_K ) {
1959
// Return an array of row objects with keys from column 1
1960
// (Duplicates are discarded)
1961
foreach ( $this->last_result as $row ) {
1962
$var_by_ref = get_object_vars( $row );
1963
$key = array_shift( $var_by_ref );
1964
if ( ! isset( $new_array[ $key ] ) )
1965
$new_array[ $key ] = $row;
1968
} elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1969
// Return an integer-keyed array of...
1970
if ( $this->last_result ) {
1971
foreach( (array) $this->last_result as $row ) {
1972
if ( $output == ARRAY_N ) {
1973
// ...integer-keyed row arrays
1974
$new_array[] = array_values( get_object_vars( $row ) );
1976
// ...column name-keyed row arrays
1977
$new_array[] = get_object_vars( $row );
1982
} elseif ( strtoupper( $output ) === OBJECT ) {
1983
// Back compat for OBJECT being previously case insensitive.
1984
return $this->last_result;
1990
* Load the column metadata from the last query.
1996
protected function load_col_info() {
1997
if ( $this->col_info )
2000
if ( $this->use_mysqli ) {
2001
for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
2002
$this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
2005
for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
2006
$this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
2012
* Retrieve column metadata from the last query.
2016
* @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
2017
* @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
2018
* @return mixed Column Results
2020
public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
2021
$this->load_col_info();
2023
if ( $this->col_info ) {
2024
if ( $col_offset == -1 ) {
2026
$new_array = array();
2027
foreach( (array) $this->col_info as $col ) {
2028
$new_array[$i] = $col->{$info_type};
2033
return $this->col_info[$col_offset]->{$info_type};
2039
* Starts the timer, for debugging purposes.
2045
public function timer_start() {
2046
$this->time_start = microtime( true );
2051
* Stops the debugging timer.
2055
* @return float Total time spent on the query, in seconds
2057
public function timer_stop() {
2058
return ( microtime( true ) - $this->time_start );
2062
* Wraps errors in a nice header and footer and dies.
2064
* Will not die if wpdb::$show_errors is false.
2068
* @param string $message The Error message
2069
* @param string $error_code Optional. A Computer readable string to identify the error.
2070
* @return false|void
2072
public function bail( $message, $error_code = '500' ) {
2073
if ( !$this->show_errors ) {
2074
if ( class_exists( 'WP_Error' ) )
2075
$this->error = new WP_Error($error_code, $message);
2077
$this->error = $message;
2084
* Whether MySQL database is at least the required minimum version.
2088
* @uses $required_mysql_version
2092
public function check_database_version() {
2093
global $wp_version, $required_mysql_version;
2094
// Make sure the server has the required MySQL version
2095
if ( version_compare($this->db_version(), $required_mysql_version, '<') )
2096
return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
2100
* Whether the database supports collation.
2102
* Called when WordPress is generating the table scheme.
2106
* @deprecated Use wpdb::has_cap( 'collation' )
2108
* @return bool True if collation is supported, false if version does not
2110
public function supports_collation() {
2111
_deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
2112
return $this->has_cap( 'collation' );
2116
* The database character collate.
2120
* @return string The database character collate.
2122
public function get_charset_collate() {
2123
$charset_collate = '';
2125
if ( ! empty( $this->charset ) )
2126
$charset_collate = "DEFAULT CHARACTER SET $this->charset";
2127
if ( ! empty( $this->collate ) )
2128
$charset_collate .= " COLLATE $this->collate";
2130
return $charset_collate;
2134
* Determine if a database supports a particular feature.
2137
* @see wpdb::db_version()
2139
* @param string $db_cap The feature to check for.
2142
public function has_cap( $db_cap ) {
2143
$version = $this->db_version();
2145
switch ( strtolower( $db_cap ) ) {
2146
case 'collation' : // @since 2.5.0
2147
case 'group_concat' : // @since 2.7.0
2148
case 'subqueries' : // @since 2.7.0
2149
return version_compare( $version, '4.1', '>=' );
2150
case 'set_charset' :
2151
return version_compare( $version, '5.0.7', '>=' );
2158
* Retrieve the name of the function that called wpdb.
2160
* Searches up the list of functions until it reaches
2161
* the one that would most logically had called this method.
2165
* @return string The name of the calling function
2167
public function get_caller() {
2168
return wp_debug_backtrace_summary( __CLASS__ );
2172
* The database version number.
2176
* @return false|string false on failure, version number on success
2178
public function db_version() {
2179
if ( $this->use_mysqli ) {
2180
$server_info = mysqli_get_server_info( $this->dbh );
2182
$server_info = mysql_get_server_info( $this->dbh );
2184
return preg_replace( '/[^0-9.].*/', '', $server_info );