5 * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
15 define( 'EZSQL_VERSION', 'WP1.25' );
20 define( 'OBJECT', 'OBJECT', true );
25 define( 'OBJECT_K', 'OBJECT_K' );
30 define( 'ARRAY_A', 'ARRAY_A' );
35 define( 'ARRAY_N', 'ARRAY_N' );
38 * WordPress Database Access Abstraction Object
40 * It is possible to replace this class with your own
41 * by setting the $wpdb global variable in wp-content/db.php
42 * file to your class. The wpdb class will still be included,
43 * so you can extend it or simply use your own.
45 * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
48 * @subpackage Database
54 * Whether to show SQL/DB errors
60 var $show_errors = false;
63 * Whether to suppress errors during the DB bootstrapping.
69 var $suppress_errors = false;
72 * The last error during query.
80 * Amount of queries made
89 * Count of rows returned by previous query
98 * Count of affected rows by previous query
104 var $rows_affected = 0;
107 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
125 * Results of the last query made
134 * MySQL result, which is either a resource or boolean.
143 * Saved info on the table column
152 * Saved queries that were executed
161 * WordPress table prefix
163 * You can set this to have multiple WordPress installations
164 * in a single database. The second reason is for possible
165 * security precautions.
174 * Whether the database queries are ready to start executing.
183 * {@internal Missing Description}}
192 * {@internal Missing Description}}
201 * List of WordPress per-blog tables
205 * @see wpdb::tables()
208 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
209 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
212 * List of deprecated WordPress tables
214 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
218 * @see wpdb::tables()
221 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
224 * List of WordPress global tables
228 * @see wpdb::tables()
231 var $global_tables = array( 'users', 'usermeta' );
234 * List of Multisite global tables
238 * @see wpdb::tables()
241 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
242 'sitecategories', 'registration_log', 'blog_versions' );
245 * WordPress Comments table
254 * WordPress Comment Metadata table
263 * WordPress Links table
272 * WordPress Options table
281 * WordPress Post Metadata table
290 * WordPress Posts table
299 * WordPress Terms table
308 * WordPress Term Relationships table
314 var $term_relationships;
317 * WordPress Term Taxonomy table
326 * Global and Multisite tables
330 * WordPress User Metadata table
339 * WordPress Users table
348 * Multisite Blogs table
357 * Multisite Blog Versions table
366 * Multisite Registration Log table
372 var $registration_log;
375 * Multisite Signups table
384 * Multisite Sites table
393 * Multisite Sitewide Terms table
402 * Multisite Site Metadata table
411 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
413 * Keys are column names, values are format types: 'ID' => '%d'
416 * @see wpdb::prepare()
417 * @see wpdb::insert()
418 * @see wpdb::update()
419 * @see wpdb::delete()
420 * @see wp_set_wpdb_vars()
424 var $field_types = array();
427 * Database table columns charset
436 * Database table columns collate
445 * Whether to use mysql_real_escape_string
451 var $real_escape = false;
469 protected $dbpassword;
499 * A textual description of the last query/get_row/get_var call
508 * Whether MySQL is used as the database engine.
510 * Set in WPDB::db_connect() to true, by default. This is used when checking
511 * against the required MySQL version for WordPress. Normally, a replacement
512 * database drop-in (db.php) will skip these checks, but setting this to true
513 * will force the checks to occur.
519 public $is_mysql = null;
522 * Connects to the database server and selects a database
524 * PHP5 style constructor for compatibility with PHP5. Does
525 * the actual setting up of the class properties and connection
528 * @link http://core.trac.wordpress.org/ticket/3354
531 * @param string $dbuser MySQL database user
532 * @param string $dbpassword MySQL database password
533 * @param string $dbname MySQL database name
534 * @param string $dbhost MySQL database host
536 function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
537 register_shutdown_function( array( $this, '__destruct' ) );
540 $this->show_errors();
542 $this->init_charset();
544 $this->dbuser = $dbuser;
545 $this->dbpassword = $dbpassword;
546 $this->dbname = $dbname;
547 $this->dbhost = $dbhost;
553 * PHP5 style destructor and will run when database object is destroyed.
555 * @see wpdb::__construct()
559 function __destruct() {
564 * PHP5 style magic getter, used to lazy-load expensive data.
568 * @param string $name The private member to get, and optionally process
569 * @return mixed The private member
571 function __get( $name ) {
572 if ( 'col_info' == $name )
573 $this->load_col_info();
579 * Magic function, for backwards compatibility
583 * @param string $name The private member to set
584 * @param mixed $value The value to set
586 function __set( $name, $value ) {
587 $this->$name = $value;
591 * Magic function, for backwards compatibility
595 * @param string $name The private member to check
597 * @return bool If the member is set or not
599 function __isset( $name ) {
600 return isset( $this->$name );
604 * Magic function, for backwards compatibility
608 * @param string $name The private member to unset
610 function __unset( $name ) {
611 unset( $this->$name );
615 * Set $this->charset and $this->collate
619 function init_charset() {
620 if ( function_exists('is_multisite') && is_multisite() ) {
621 $this->charset = 'utf8';
622 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
623 $this->collate = DB_COLLATE;
625 $this->collate = 'utf8_general_ci';
626 } elseif ( defined( 'DB_COLLATE' ) ) {
627 $this->collate = DB_COLLATE;
630 if ( defined( 'DB_CHARSET' ) )
631 $this->charset = DB_CHARSET;
635 * Sets the connection's character set.
639 * @param resource $dbh The resource given by mysql_connect
640 * @param string $charset The character set (optional)
641 * @param string $collate The collation (optional)
643 function set_charset($dbh, $charset = null, $collate = null) {
644 if ( !isset($charset) )
645 $charset = $this->charset;
646 if ( !isset($collate) )
647 $collate = $this->collate;
648 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
649 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
650 mysql_set_charset( $charset, $dbh );
651 $this->real_escape = true;
653 $query = $this->prepare( 'SET NAMES %s', $charset );
654 if ( ! empty( $collate ) )
655 $query .= $this->prepare( ' COLLATE %s', $collate );
656 mysql_query( $query, $dbh );
662 * Sets the table prefix for the WordPress tables.
666 * @param string $prefix Alphanumeric name for the new prefix.
667 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
668 * @return string|WP_Error Old prefix or WP_Error on error
670 function set_prefix( $prefix, $set_table_names = true ) {
672 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
673 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
675 $old_prefix = is_multisite() ? '' : $prefix;
677 if ( isset( $this->base_prefix ) )
678 $old_prefix = $this->base_prefix;
680 $this->base_prefix = $prefix;
682 if ( $set_table_names ) {
683 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
684 $this->$table = $prefixed_table;
686 if ( is_multisite() && empty( $this->blogid ) )
689 $this->prefix = $this->get_blog_prefix();
691 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
692 $this->$table = $prefixed_table;
694 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
695 $this->$table = $prefixed_table;
705 * @param int $blog_id
706 * @param int $site_id Optional.
707 * @return string previous blog id
709 function set_blog_id( $blog_id, $site_id = 0 ) {
710 if ( ! empty( $site_id ) )
711 $this->siteid = $site_id;
713 $old_blog_id = $this->blogid;
714 $this->blogid = $blog_id;
716 $this->prefix = $this->get_blog_prefix();
718 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
719 $this->$table = $prefixed_table;
721 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
722 $this->$table = $prefixed_table;
730 * @uses is_multisite()
732 * @param int $blog_id Optional.
733 * @return string Blog prefix.
735 function get_blog_prefix( $blog_id = null ) {
736 if ( is_multisite() ) {
737 if ( null === $blog_id )
738 $blog_id = $this->blogid;
739 $blog_id = (int) $blog_id;
740 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
741 return $this->base_prefix;
743 return $this->base_prefix . $blog_id . '_';
745 return $this->base_prefix;
750 * Returns an array of WordPress tables.
752 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
753 * override the WordPress users and usermeta tables that would otherwise
754 * be determined by the prefix.
756 * The scope argument can take one of the following:
758 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
759 * 'blog' - returns the blog-level tables for the queried blog.
760 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
761 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
762 * 'old' - returns tables which are deprecated.
765 * @uses wpdb::$tables
766 * @uses wpdb::$old_tables
767 * @uses wpdb::$global_tables
768 * @uses wpdb::$ms_global_tables
769 * @uses is_multisite()
771 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
772 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
773 * prefix is requested, then the custom users and usermeta tables will be mapped.
774 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
775 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
777 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
780 $tables = array_merge( $this->global_tables, $this->tables );
781 if ( is_multisite() )
782 $tables = array_merge( $tables, $this->ms_global_tables );
785 $tables = $this->tables;
788 $tables = $this->global_tables;
789 if ( is_multisite() )
790 $tables = array_merge( $tables, $this->ms_global_tables );
793 $tables = $this->ms_global_tables;
796 $tables = $this->old_tables;
805 $blog_id = $this->blogid;
806 $blog_prefix = $this->get_blog_prefix( $blog_id );
807 $base_prefix = $this->base_prefix;
808 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
809 foreach ( $tables as $k => $table ) {
810 if ( in_array( $table, $global_tables ) )
811 $tables[ $table ] = $base_prefix . $table;
813 $tables[ $table ] = $blog_prefix . $table;
814 unset( $tables[ $k ] );
817 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
818 $tables['users'] = CUSTOM_USER_TABLE;
820 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
821 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
828 * Selects a database using the current database connection.
830 * The database name will be changed based on the current database
831 * connection. On failure, the execution will bail and display an DB error.
835 * @param string $db MySQL database name
836 * @param resource $dbh Optional link identifier.
837 * @return null Always null.
839 function select( $db, $dbh = null ) {
843 if ( !@mysql_select_db( $db, $dbh ) ) {
844 $this->ready = false;
845 wp_load_translations_early();
846 $this->bail( sprintf( __( '<h1>Can’t select database</h1>
847 <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>
849 <li>Are you sure it exists?</li>
850 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
851 <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>
853 <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="http://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
859 * Weak escape, using addslashes()
865 * @param string $string
868 function _weak_escape( $string ) {
869 return addslashes( $string );
873 * Real escape, using mysql_real_escape_string() or addslashes()
875 * @see mysql_real_escape_string()
880 * @param string $string to escape
881 * @return string escaped
883 function _real_escape( $string ) {
884 if ( $this->dbh && $this->real_escape )
885 return mysql_real_escape_string( $string, $this->dbh );
887 return addslashes( $string );
891 * Escape data. Works on arrays.
893 * @uses wpdb::_escape()
894 * @uses wpdb::_real_escape()
898 * @param string|array $data
899 * @return string|array escaped
901 function _escape( $data ) {
902 if ( is_array( $data ) ) {
903 foreach ( (array) $data as $k => $v ) {
905 $data[$k] = $this->_escape( $v );
907 $data[$k] = $this->_real_escape( $v );
910 $data = $this->_real_escape( $data );
917 * Escapes content for insertion into the database using addslashes(), for security.
922 * @param string|array $data to escape
923 * @return string|array escaped as query safe string
925 function escape( $data ) {
926 if ( is_array( $data ) ) {
927 foreach ( (array) $data as $k => $v ) {
928 if ( is_array( $v ) )
929 $data[$k] = $this->escape( $v );
931 $data[$k] = $this->_weak_escape( $v );
934 $data = $this->_weak_escape( $data );
941 * Escapes content by reference for insertion into the database, for security
943 * @uses wpdb::_real_escape()
945 * @param string $string to escape
948 function escape_by_ref( &$string ) {
949 if ( ! is_float( $string ) )
950 $string = $this->_real_escape( $string );
954 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
956 * The following directives can be used in the query format string:
960 * %% (literal percentage sign - no argument needed)
962 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
963 * Literals (%) as parts of the query must be properly written as %%.
965 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
966 * Does not support sign, padding, alignment, width or precision specifiers.
967 * Does not support argument numbering/swapping.
969 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
971 * Both %d and %s should be left unquoted in the query string.
974 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
975 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
978 * @link http://php.net/sprintf Description of syntax.
981 * @param string $query Query statement with sprintf()-like placeholders
982 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
983 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
984 * being called like {@link http://php.net/sprintf sprintf()}.
985 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
986 * {@link http://php.net/sprintf sprintf()}.
987 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
988 * if there was something to prepare
990 function prepare( $query, $args = null ) {
991 if ( is_null( $query ) )
994 if ( func_num_args() < 2 )
995 _doing_it_wrong( 'wpdb::prepare', 'wpdb::prepare() requires at least two arguments.', '3.5' );
997 $args = func_get_args();
998 array_shift( $args );
999 // If args were passed as an array (as in vsprintf), move them up
1000 if ( isset( $args[0] ) && is_array($args[0]) )
1002 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1003 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1004 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1005 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1006 array_walk( $args, array( $this, 'escape_by_ref' ) );
1007 return @vsprintf( $query, $args );
1011 * Print SQL/DB error.
1014 * @global array $EZSQL_ERROR Stores error information of query and error string
1016 * @param string $str The error to display
1017 * @return bool False if the showing of errors is disabled.
1019 function print_error( $str = '' ) {
1020 global $EZSQL_ERROR;
1023 $str = mysql_error( $this->dbh );
1024 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1026 if ( $this->suppress_errors )
1029 wp_load_translations_early();
1031 if ( $caller = $this->get_caller() )
1032 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1034 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1036 error_log( $error_str );
1038 // Are we showing errors?
1039 if ( ! $this->show_errors )
1042 // If there is an error then take note of it
1043 if ( is_multisite() ) {
1044 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1045 if ( defined( 'ERRORLOGFILE' ) )
1046 error_log( $msg, 3, ERRORLOGFILE );
1047 if ( defined( 'DIEONDBERROR' ) )
1050 $str = htmlspecialchars( $str, ENT_QUOTES );
1051 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1053 print "<div id='error'>
1054 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1055 <code>$query</code></p>
1061 * Enables showing of database errors.
1063 * This function should be used only to enable showing of errors.
1064 * wpdb::hide_errors() should be used instead for hiding of errors. However,
1065 * this function can be used to enable and disable showing of database
1069 * @see wpdb::hide_errors()
1071 * @param bool $show Whether to show or hide errors
1072 * @return bool Old value for showing errors.
1074 function show_errors( $show = true ) {
1075 $errors = $this->show_errors;
1076 $this->show_errors = $show;
1081 * Disables showing of database errors.
1083 * By default database errors are not shown.
1086 * @see wpdb::show_errors()
1088 * @return bool Whether showing of errors was active
1090 function hide_errors() {
1091 $show = $this->show_errors;
1092 $this->show_errors = false;
1097 * Whether to suppress database errors.
1099 * By default database errors are suppressed, with a simple
1100 * call to this function they can be enabled.
1103 * @see wpdb::hide_errors()
1104 * @param bool $suppress Optional. New value. Defaults to true.
1105 * @return bool Old value
1107 function suppress_errors( $suppress = true ) {
1108 $errors = $this->suppress_errors;
1109 $this->suppress_errors = (bool) $suppress;
1114 * Kill cached query results.
1120 $this->last_result = array();
1121 $this->col_info = null;
1122 $this->last_query = null;
1124 if ( is_resource( $this->result ) )
1125 mysql_free_result( $this->result );
1129 * Connect to and select database
1133 function db_connect() {
1135 $this->is_mysql = true;
1137 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1138 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1141 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1143 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1146 if ( !$this->dbh ) {
1147 wp_load_translations_early();
1148 $this->bail( sprintf( __( "
1149 <h1>Error establishing a database connection</h1>
1150 <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>
1152 <li>Are you sure you have the correct username and password?</li>
1153 <li>Are you sure that you have typed the correct hostname?</li>
1154 <li>Are you sure that the database server is running?</li>
1156 <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='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
1157 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1162 $this->set_charset( $this->dbh );
1164 $this->ready = true;
1166 $this->select( $this->dbname, $this->dbh );
1170 * Perform a MySQL database query, using current database connection.
1172 * More information can be found on the codex page.
1176 * @param string $query Database query
1177 * @return int|false Number of rows affected/selected or false on error
1179 function query( $query ) {
1180 if ( ! $this->ready )
1183 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1184 $query = apply_filters( 'query', $query );
1189 // Log how the function was called
1190 $this->func_call = "\$db->query(\"$query\")";
1192 // Keep track of the last query for debug..
1193 $this->last_query = $query;
1195 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1196 $this->timer_start();
1198 $this->result = @mysql_query( $query, $this->dbh );
1199 $this->num_queries++;
1201 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1202 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1204 // If there is an error then take note of it..
1205 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1206 $this->print_error();
1210 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1211 $return_val = $this->result;
1212 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1213 $this->rows_affected = mysql_affected_rows( $this->dbh );
1214 // Take note of the insert_id
1215 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1216 $this->insert_id = mysql_insert_id($this->dbh);
1218 // Return number of rows affected
1219 $return_val = $this->rows_affected;
1222 while ( $row = @mysql_fetch_object( $this->result ) ) {
1223 $this->last_result[$num_rows] = $row;
1227 // Log number of rows the query returned
1228 // and return number of rows selected
1229 $this->num_rows = $num_rows;
1230 $return_val = $num_rows;
1237 * Insert a row into a table.
1240 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1241 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1245 * @see wpdb::prepare()
1246 * @see wpdb::$field_types
1247 * @see wp_set_wpdb_vars()
1249 * @param string $table table name
1250 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1251 * @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.
1252 * 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.
1253 * @return int|false The number of rows inserted, or false on error.
1255 function insert( $table, $data, $format = null ) {
1256 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1260 * Replace a row into a table.
1263 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1264 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1268 * @see wpdb::prepare()
1269 * @see wpdb::$field_types
1270 * @see wp_set_wpdb_vars()
1272 * @param string $table table name
1273 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1274 * @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.
1275 * 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.
1276 * @return int|false The number of rows affected, or false on error.
1278 function replace( $table, $data, $format = null ) {
1279 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1283 * Helper function for insert and replace.
1285 * Runs an insert or replace query based on $type argument.
1289 * @see wpdb::prepare()
1290 * @see wpdb::$field_types
1291 * @see wp_set_wpdb_vars()
1293 * @param string $table table name
1294 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1295 * @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.
1296 * 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.
1297 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1298 * @return int|false The number of rows affected, or false on error.
1300 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1301 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1303 $formats = $format = (array) $format;
1304 $fields = array_keys( $data );
1305 $formatted_fields = array();
1306 foreach ( $fields as $field ) {
1307 if ( !empty( $format ) )
1308 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1309 elseif ( isset( $this->field_types[$field] ) )
1310 $form = $this->field_types[$field];
1313 $formatted_fields[] = $form;
1315 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
1316 return $this->query( $this->prepare( $sql, $data ) );
1320 * Update a row in the table
1323 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1324 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1328 * @see wpdb::prepare()
1329 * @see wpdb::$field_types
1330 * @see wp_set_wpdb_vars()
1332 * @param string $table table name
1333 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1334 * @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".
1335 * @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.
1336 * 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.
1337 * @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.
1338 * @return int|false The number of rows updated, or false on error.
1340 function update( $table, $data, $where, $format = null, $where_format = null ) {
1341 if ( ! is_array( $data ) || ! is_array( $where ) )
1344 $formats = $format = (array) $format;
1345 $bits = $wheres = array();
1346 foreach ( (array) array_keys( $data ) as $field ) {
1347 if ( !empty( $format ) )
1348 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1349 elseif ( isset($this->field_types[$field]) )
1350 $form = $this->field_types[$field];
1353 $bits[] = "`$field` = {$form}";
1356 $where_formats = $where_format = (array) $where_format;
1357 foreach ( (array) array_keys( $where ) as $field ) {
1358 if ( !empty( $where_format ) )
1359 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1360 elseif ( isset( $this->field_types[$field] ) )
1361 $form = $this->field_types[$field];
1364 $wheres[] = "`$field` = {$form}";
1367 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1368 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1372 * Delete a row in the table
1375 * wpdb::delete( 'table', array( 'ID' => 1 ) )
1376 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1380 * @see wpdb::prepare()
1381 * @see wpdb::$field_types
1382 * @see wp_set_wpdb_vars()
1384 * @param string $table table name
1385 * @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".
1386 * @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.
1387 * @return int|false The number of rows updated, or false on error.
1389 function delete( $table, $where, $where_format = null ) {
1390 if ( ! is_array( $where ) )
1393 $bits = $wheres = array();
1395 $where_formats = $where_format = (array) $where_format;
1397 foreach ( array_keys( $where ) as $field ) {
1398 if ( !empty( $where_format ) ) {
1399 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1400 } elseif ( isset( $this->field_types[ $field ] ) ) {
1401 $form = $this->field_types[ $field ];
1406 $wheres[] = "$field = $form";
1409 $sql = "DELETE FROM $table WHERE " . implode( ' AND ', $wheres );
1410 return $this->query( $this->prepare( $sql, $where ) );
1415 * Retrieve one variable from the database.
1417 * Executes a SQL query and returns the value from the SQL result.
1418 * 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.
1419 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1423 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1424 * @param int $x Optional. Column of value to return. Indexed from 0.
1425 * @param int $y Optional. Row of value to return. Indexed from 0.
1426 * @return string|null Database query result (as string), or null on failure
1428 function get_var( $query = null, $x = 0, $y = 0 ) {
1429 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1431 $this->query( $query );
1433 // Extract var out of cached results based x,y vals
1434 if ( !empty( $this->last_result[$y] ) ) {
1435 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1438 // If there is a value return it else return null
1439 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1443 * Retrieve one row from the database.
1445 * Executes a SQL query and returns the row from the SQL result.
1449 * @param string|null $query SQL query.
1450 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1451 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1452 * @param int $y Optional. Row to return. Indexed from 0.
1453 * @return mixed Database query result in format specified by $output or null on failure
1455 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1456 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1458 $this->query( $query );
1462 if ( !isset( $this->last_result[$y] ) )
1465 if ( $output == OBJECT ) {
1466 return $this->last_result[$y] ? $this->last_result[$y] : null;
1467 } elseif ( $output == ARRAY_A ) {
1468 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1469 } elseif ( $output == ARRAY_N ) {
1470 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1472 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
1477 * Retrieve one column from the database.
1479 * Executes a SQL query and returns the column from the SQL result.
1480 * If the SQL result contains more than one column, this function returns the column specified.
1481 * If $query is null, this function returns the specified column from the previous SQL result.
1485 * @param string|null $query Optional. SQL query. Defaults to previous query.
1486 * @param int $x Optional. Column to return. Indexed from 0.
1487 * @return array Database query result. Array indexed from 0 by SQL result row number.
1489 function get_col( $query = null , $x = 0 ) {
1491 $this->query( $query );
1493 $new_array = array();
1494 // Extract the column values
1495 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1496 $new_array[$i] = $this->get_var( null, $x, $i );
1502 * Retrieve an entire SQL result set from the database (i.e., many rows)
1504 * Executes a SQL query and returns the entire SQL result.
1508 * @param string $query SQL query.
1509 * @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.
1510 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1511 * 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.
1512 * @return mixed Database query results
1514 function get_results( $query = null, $output = OBJECT ) {
1515 $this->func_call = "\$db->get_results(\"$query\", $output)";
1518 $this->query( $query );
1522 $new_array = array();
1523 if ( $output == OBJECT ) {
1524 // Return an integer-keyed array of row objects
1525 return $this->last_result;
1526 } elseif ( $output == OBJECT_K ) {
1527 // Return an array of row objects with keys from column 1
1528 // (Duplicates are discarded)
1529 foreach ( $this->last_result as $row ) {
1530 $var_by_ref = get_object_vars( $row );
1531 $key = array_shift( $var_by_ref );
1532 if ( ! isset( $new_array[ $key ] ) )
1533 $new_array[ $key ] = $row;
1536 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1537 // Return an integer-keyed array of...
1538 if ( $this->last_result ) {
1539 foreach( (array) $this->last_result as $row ) {
1540 if ( $output == ARRAY_N ) {
1541 // ...integer-keyed row arrays
1542 $new_array[] = array_values( get_object_vars( $row ) );
1544 // ...column name-keyed row arrays
1545 $new_array[] = get_object_vars( $row );
1555 * Load the column metadata from the last query.
1561 protected function load_col_info() {
1562 if ( $this->col_info )
1565 for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
1566 $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
1571 * Retrieve column metadata from the last query.
1575 * @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
1576 * @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
1577 * @return mixed Column Results
1579 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1580 $this->load_col_info();
1582 if ( $this->col_info ) {
1583 if ( $col_offset == -1 ) {
1585 $new_array = array();
1586 foreach( (array) $this->col_info as $col ) {
1587 $new_array[$i] = $col->{$info_type};
1592 return $this->col_info[$col_offset]->{$info_type};
1598 * Starts the timer, for debugging purposes.
1604 function timer_start() {
1605 $this->time_start = microtime( true );
1610 * Stops the debugging timer.
1614 * @return float Total time spent on the query, in seconds
1616 function timer_stop() {
1617 return ( microtime( true ) - $this->time_start );
1621 * Wraps errors in a nice header and footer and dies.
1623 * Will not die if wpdb::$show_errors is false.
1627 * @param string $message The Error message
1628 * @param string $error_code Optional. A Computer readable string to identify the error.
1629 * @return false|void
1631 function bail( $message, $error_code = '500' ) {
1632 if ( !$this->show_errors ) {
1633 if ( class_exists( 'WP_Error' ) )
1634 $this->error = new WP_Error($error_code, $message);
1636 $this->error = $message;
1643 * Whether MySQL database is at least the required minimum version.
1647 * @uses $required_mysql_version
1651 function check_database_version() {
1652 global $wp_version, $required_mysql_version;
1653 // Make sure the server has the required MySQL version
1654 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1655 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1659 * Whether the database supports collation.
1661 * Called when WordPress is generating the table scheme.
1665 * @deprecated Use wpdb::has_cap( 'collation' )
1667 * @return bool True if collation is supported, false if version does not
1669 function supports_collation() {
1670 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
1671 return $this->has_cap( 'collation' );
1675 * The database character collate.
1679 * @return string The database character collate.
1681 public function get_charset_collate() {
1682 $charset_collate = '';
1684 if ( ! empty( $this->charset ) )
1685 $charset_collate = "DEFAULT CHARACTER SET $this->charset";
1686 if ( ! empty( $this->collate ) )
1687 $charset_collate .= " COLLATE $this->collate";
1689 return $charset_collate;
1693 * Determine if a database supports a particular feature
1696 * @see wpdb::db_version()
1698 * @param string $db_cap the feature
1701 function has_cap( $db_cap ) {
1702 $version = $this->db_version();
1704 switch ( strtolower( $db_cap ) ) {
1705 case 'collation' : // @since 2.5.0
1706 case 'group_concat' : // @since 2.7
1707 case 'subqueries' : // @since 2.7
1708 return version_compare( $version, '4.1', '>=' );
1709 case 'set_charset' :
1710 return version_compare($version, '5.0.7', '>=');
1717 * Retrieve the name of the function that called wpdb.
1719 * Searches up the list of functions until it reaches
1720 * the one that would most logically had called this method.
1724 * @return string The name of the calling function
1726 function get_caller() {
1727 return wp_debug_backtrace_summary( __CLASS__ );
1731 * The database version number.
1735 * @return false|string false on failure, version number on success
1737 function db_version() {
1738 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );