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).
116 * Saved result of the last query made
125 * Results of the last query made
134 * Saved info on the table column
143 * Saved queries that were executed
152 * WordPress table prefix
154 * You can set this to have multiple WordPress installations
155 * in a single database. The second reason is for possible
156 * security precautions.
165 * Whether the database queries are ready to start executing.
174 * {@internal Missing Description}}
183 * {@internal Missing Description}}
192 * List of WordPress per-blog tables
196 * @see wpdb::tables()
199 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
200 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
203 * List of deprecated WordPress tables
205 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
209 * @see wpdb::tables()
212 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
215 * List of WordPress global tables
219 * @see wpdb::tables()
222 var $global_tables = array( 'users', 'usermeta' );
225 * List of Multisite global tables
229 * @see wpdb::tables()
232 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
233 'sitecategories', 'registration_log', 'blog_versions' );
236 * WordPress Comments table
245 * WordPress Comment Metadata table
254 * WordPress Links table
263 * WordPress Options table
272 * WordPress Post Metadata table
281 * WordPress Posts table
290 * WordPress Terms table
299 * WordPress Term Relationships table
305 var $term_relationships;
308 * WordPress Term Taxonomy table
317 * Global and Multisite tables
321 * WordPress User Metadata table
330 * WordPress Users table
339 * Multisite Blogs table
348 * Multisite Blog Versions table
357 * Multisite Registration Log table
363 var $registration_log;
366 * Multisite Signups table
375 * Multisite Sites table
384 * Multisite Sitewide Terms table
393 * Multisite Site Metadata table
402 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
404 * Keys are column names, values are format types: 'ID' => '%d'
407 * @see wpdb::prepare()
408 * @see wpdb::insert()
409 * @see wpdb::update()
410 * @see wpdb::delete()
411 * @see wp_set_wpdb_vars()
415 var $field_types = array();
418 * Database table columns charset
427 * Database table columns collate
436 * Whether to use mysql_real_escape_string
442 var $real_escape = false;
454 * A textual description of the last query/get_row/get_var call
463 * Whether MySQL is used as the database engine.
465 * Set in WPDB::db_connect() to true, by default. This is used when checking
466 * against the required MySQL version for WordPress. Normally, a replacement
467 * database drop-in (db.php) will skip these checks, but setting this to true
468 * will force the checks to occur.
474 public $is_mysql = null;
477 * Connects to the database server and selects a database
479 * PHP5 style constructor for compatibility with PHP5. Does
480 * the actual setting up of the class properties and connection
483 * @link http://core.trac.wordpress.org/ticket/3354
486 * @param string $dbuser MySQL database user
487 * @param string $dbpassword MySQL database password
488 * @param string $dbname MySQL database name
489 * @param string $dbhost MySQL database host
491 function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
492 register_shutdown_function( array( &$this, '__destruct' ) );
495 $this->show_errors();
497 $this->init_charset();
499 $this->dbuser = $dbuser;
500 $this->dbpassword = $dbpassword;
501 $this->dbname = $dbname;
502 $this->dbhost = $dbhost;
508 * PHP5 style destructor and will run when database object is destroyed.
510 * @see wpdb::__construct()
514 function __destruct() {
519 * Set $this->charset and $this->collate
523 function init_charset() {
524 if ( function_exists('is_multisite') && is_multisite() ) {
525 $this->charset = 'utf8';
526 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
527 $this->collate = DB_COLLATE;
529 $this->collate = 'utf8_general_ci';
530 } elseif ( defined( 'DB_COLLATE' ) ) {
531 $this->collate = DB_COLLATE;
534 if ( defined( 'DB_CHARSET' ) )
535 $this->charset = DB_CHARSET;
539 * Sets the connection's character set.
543 * @param resource $dbh The resource given by mysql_connect
544 * @param string $charset The character set (optional)
545 * @param string $collate The collation (optional)
547 function set_charset($dbh, $charset = null, $collate = null) {
548 if ( !isset($charset) )
549 $charset = $this->charset;
550 if ( !isset($collate) )
551 $collate = $this->collate;
552 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
553 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
554 mysql_set_charset( $charset, $dbh );
555 $this->real_escape = true;
557 $query = $this->prepare( 'SET NAMES %s', $charset );
558 if ( ! empty( $collate ) )
559 $query .= $this->prepare( ' COLLATE %s', $collate );
560 mysql_query( $query, $dbh );
566 * Sets the table prefix for the WordPress tables.
570 * @param string $prefix Alphanumeric name for the new prefix.
571 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
572 * @return string|WP_Error Old prefix or WP_Error on error
574 function set_prefix( $prefix, $set_table_names = true ) {
576 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
577 return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
579 $old_prefix = is_multisite() ? '' : $prefix;
581 if ( isset( $this->base_prefix ) )
582 $old_prefix = $this->base_prefix;
584 $this->base_prefix = $prefix;
586 if ( $set_table_names ) {
587 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
588 $this->$table = $prefixed_table;
590 if ( is_multisite() && empty( $this->blogid ) )
593 $this->prefix = $this->get_blog_prefix();
595 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
596 $this->$table = $prefixed_table;
598 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
599 $this->$table = $prefixed_table;
609 * @param int $blog_id
610 * @param int $site_id Optional.
611 * @return string previous blog id
613 function set_blog_id( $blog_id, $site_id = 0 ) {
614 if ( ! empty( $site_id ) )
615 $this->siteid = $site_id;
617 $old_blog_id = $this->blogid;
618 $this->blogid = $blog_id;
620 $this->prefix = $this->get_blog_prefix();
622 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
623 $this->$table = $prefixed_table;
625 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
626 $this->$table = $prefixed_table;
634 * @uses is_multisite()
636 * @param int $blog_id Optional.
637 * @return string Blog prefix.
639 function get_blog_prefix( $blog_id = null ) {
640 if ( is_multisite() ) {
641 if ( null === $blog_id )
642 $blog_id = $this->blogid;
643 $blog_id = (int) $blog_id;
644 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
645 return $this->base_prefix;
647 return $this->base_prefix . $blog_id . '_';
649 return $this->base_prefix;
654 * Returns an array of WordPress tables.
656 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
657 * override the WordPress users and usermeta tables that would otherwise
658 * be determined by the prefix.
660 * The scope argument can take one of the following:
662 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
663 * 'blog' - returns the blog-level tables for the queried blog.
664 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
665 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
666 * 'old' - returns tables which are deprecated.
669 * @uses wpdb::$tables
670 * @uses wpdb::$old_tables
671 * @uses wpdb::$global_tables
672 * @uses wpdb::$ms_global_tables
673 * @uses is_multisite()
675 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
676 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
677 * prefix is requested, then the custom users and usermeta tables will be mapped.
678 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
679 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
681 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
684 $tables = array_merge( $this->global_tables, $this->tables );
685 if ( is_multisite() )
686 $tables = array_merge( $tables, $this->ms_global_tables );
689 $tables = $this->tables;
692 $tables = $this->global_tables;
693 if ( is_multisite() )
694 $tables = array_merge( $tables, $this->ms_global_tables );
697 $tables = $this->ms_global_tables;
700 $tables = $this->old_tables;
709 $blog_id = $this->blogid;
710 $blog_prefix = $this->get_blog_prefix( $blog_id );
711 $base_prefix = $this->base_prefix;
712 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
713 foreach ( $tables as $k => $table ) {
714 if ( in_array( $table, $global_tables ) )
715 $tables[ $table ] = $base_prefix . $table;
717 $tables[ $table ] = $blog_prefix . $table;
718 unset( $tables[ $k ] );
721 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
722 $tables['users'] = CUSTOM_USER_TABLE;
724 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
725 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
732 * Selects a database using the current database connection.
734 * The database name will be changed based on the current database
735 * connection. On failure, the execution will bail and display an DB error.
739 * @param string $db MySQL database name
740 * @param resource $dbh Optional link identifier.
741 * @return null Always null.
743 function select( $db, $dbh = null ) {
747 if ( !@mysql_select_db( $db, $dbh ) ) {
748 $this->ready = false;
749 wp_load_translations_early();
750 $this->bail( sprintf( __( '<h1>Can’t select database</h1>
751 <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>
753 <li>Are you sure it exists?</li>
754 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
755 <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>
757 <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' );
763 * Weak escape, using addslashes()
769 * @param string $string
772 function _weak_escape( $string ) {
773 return addslashes( $string );
777 * Real escape, using mysql_real_escape_string() or addslashes()
779 * @see mysql_real_escape_string()
784 * @param string $string to escape
785 * @return string escaped
787 function _real_escape( $string ) {
788 if ( $this->dbh && $this->real_escape )
789 return mysql_real_escape_string( $string, $this->dbh );
791 return addslashes( $string );
795 * Escape data. Works on arrays.
797 * @uses wpdb::_escape()
798 * @uses wpdb::_real_escape()
802 * @param string|array $data
803 * @return string|array escaped
805 function _escape( $data ) {
806 if ( is_array( $data ) ) {
807 foreach ( (array) $data as $k => $v ) {
809 $data[$k] = $this->_escape( $v );
811 $data[$k] = $this->_real_escape( $v );
814 $data = $this->_real_escape( $data );
821 * Escapes content for insertion into the database using addslashes(), for security.
826 * @param string|array $data to escape
827 * @return string|array escaped as query safe string
829 function escape( $data ) {
830 if ( is_array( $data ) ) {
831 foreach ( (array) $data as $k => $v ) {
832 if ( is_array( $v ) )
833 $data[$k] = $this->escape( $v );
835 $data[$k] = $this->_weak_escape( $v );
838 $data = $this->_weak_escape( $data );
845 * Escapes content by reference for insertion into the database, for security
847 * @uses wpdb::_real_escape()
849 * @param string $string to escape
852 function escape_by_ref( &$string ) {
853 $string = $this->_real_escape( $string );
857 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
859 * The following directives can be used in the query format string:
863 * %% (literal percentage sign - no argument needed)
865 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
866 * Literals (%) as parts of the query must be properly written as %%.
868 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
869 * Does not support sign, padding, alignment, width or precision specifiers.
870 * Does not support argument numbering/swapping.
872 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
874 * Both %d and %s should be left unquoted in the query string.
877 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
878 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
881 * @link http://php.net/sprintf Description of syntax.
884 * @param string $query Query statement with sprintf()-like placeholders
885 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
886 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
887 * being called like {@link http://php.net/sprintf sprintf()}.
888 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
889 * {@link http://php.net/sprintf sprintf()}.
890 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
891 * if there was something to prepare
893 function prepare( $query = null ) { // ( $query, *$args )
894 if ( is_null( $query ) )
897 $args = func_get_args();
898 array_shift( $args );
899 // If args were passed as an array (as in vsprintf), move them up
900 if ( isset( $args[0] ) && is_array($args[0]) )
902 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
903 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
904 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
905 array_walk( $args, array( &$this, 'escape_by_ref' ) );
906 return @vsprintf( $query, $args );
910 * Print SQL/DB error.
913 * @global array $EZSQL_ERROR Stores error information of query and error string
915 * @param string $str The error to display
916 * @return bool False if the showing of errors is disabled.
918 function print_error( $str = '' ) {
922 $str = mysql_error( $this->dbh );
923 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
925 if ( $this->suppress_errors )
928 wp_load_translations_early();
930 if ( $caller = $this->get_caller() )
931 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
933 $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
935 if ( function_exists( 'error_log' )
936 && ( $log_file = @ini_get( 'error_log' ) )
937 && ( 'syslog' == $log_file || @is_writable( $log_file ) )
939 @error_log( $error_str );
941 // Are we showing errors?
942 if ( ! $this->show_errors )
945 // If there is an error then take note of it
946 if ( is_multisite() ) {
947 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
948 if ( defined( 'ERRORLOGFILE' ) )
949 error_log( $msg, 3, ERRORLOGFILE );
950 if ( defined( 'DIEONDBERROR' ) )
953 $str = htmlspecialchars( $str, ENT_QUOTES );
954 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
956 print "<div id='error'>
957 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
958 <code>$query</code></p>
964 * Enables showing of database errors.
966 * This function should be used only to enable showing of errors.
967 * wpdb::hide_errors() should be used instead for hiding of errors. However,
968 * this function can be used to enable and disable showing of database
972 * @see wpdb::hide_errors()
974 * @param bool $show Whether to show or hide errors
975 * @return bool Old value for showing errors.
977 function show_errors( $show = true ) {
978 $errors = $this->show_errors;
979 $this->show_errors = $show;
984 * Disables showing of database errors.
986 * By default database errors are not shown.
989 * @see wpdb::show_errors()
991 * @return bool Whether showing of errors was active
993 function hide_errors() {
994 $show = $this->show_errors;
995 $this->show_errors = false;
1000 * Whether to suppress database errors.
1002 * By default database errors are suppressed, with a simple
1003 * call to this function they can be enabled.
1006 * @see wpdb::hide_errors()
1007 * @param bool $suppress Optional. New value. Defaults to true.
1008 * @return bool Old value
1010 function suppress_errors( $suppress = true ) {
1011 $errors = $this->suppress_errors;
1012 $this->suppress_errors = (bool) $suppress;
1017 * Kill cached query results.
1023 $this->last_result = array();
1024 $this->col_info = null;
1025 $this->last_query = null;
1029 * Connect to and select database
1033 function db_connect() {
1035 $this->is_mysql = true;
1038 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1040 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1043 if ( !$this->dbh ) {
1044 wp_load_translations_early();
1045 $this->bail( sprintf( __( "
1046 <h1>Error establishing a database connection</h1>
1047 <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>
1049 <li>Are you sure you have the correct username and password?</li>
1050 <li>Are you sure that you have typed the correct hostname?</li>
1051 <li>Are you sure that the database server is running?</li>
1053 <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>
1054 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1059 $this->set_charset( $this->dbh );
1061 $this->ready = true;
1063 $this->select( $this->dbname, $this->dbh );
1067 * Perform a MySQL database query, using current database connection.
1069 * More information can be found on the codex page.
1073 * @param string $query Database query
1074 * @return int|false Number of rows affected/selected or false on error
1076 function query( $query ) {
1077 if ( ! $this->ready )
1080 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1081 $query = apply_filters( 'query', $query );
1086 // Log how the function was called
1087 $this->func_call = "\$db->query(\"$query\")";
1089 // Keep track of the last query for debug..
1090 $this->last_query = $query;
1092 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1093 $this->timer_start();
1095 $this->result = @mysql_query( $query, $this->dbh );
1096 $this->num_queries++;
1098 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1099 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1101 // If there is an error then take note of it..
1102 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1103 $this->print_error();
1107 if ( preg_match( '/^\s*(create|alter|truncate|drop) /i', $query ) ) {
1108 $return_val = $this->result;
1109 } elseif ( preg_match( '/^\s*(insert|delete|update|replace) /i', $query ) ) {
1110 $this->rows_affected = mysql_affected_rows( $this->dbh );
1111 // Take note of the insert_id
1112 if ( preg_match( '/^\s*(insert|replace) /i', $query ) ) {
1113 $this->insert_id = mysql_insert_id($this->dbh);
1115 // Return number of rows affected
1116 $return_val = $this->rows_affected;
1119 while ( $i < @mysql_num_fields( $this->result ) ) {
1120 $this->col_info[$i] = @mysql_fetch_field( $this->result );
1124 while ( $row = @mysql_fetch_object( $this->result ) ) {
1125 $this->last_result[$num_rows] = $row;
1129 @mysql_free_result( $this->result );
1131 // Log number of rows the query returned
1132 // and return number of rows selected
1133 $this->num_rows = $num_rows;
1134 $return_val = $num_rows;
1141 * Insert a row into a table.
1144 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1145 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1149 * @see wpdb::prepare()
1150 * @see wpdb::$field_types
1151 * @see wp_set_wpdb_vars()
1153 * @param string $table table name
1154 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1155 * @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.
1156 * 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.
1157 * @return int|false The number of rows inserted, or false on error.
1159 function insert( $table, $data, $format = null ) {
1160 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1164 * Replace a row into a table.
1167 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1168 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1172 * @see wpdb::prepare()
1173 * @see wpdb::$field_types
1174 * @see wp_set_wpdb_vars()
1176 * @param string $table table name
1177 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1178 * @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.
1179 * 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.
1180 * @return int|false The number of rows affected, or false on error.
1182 function replace( $table, $data, $format = null ) {
1183 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1187 * Helper function for insert and replace.
1189 * Runs an insert or replace query based on $type argument.
1193 * @see wpdb::prepare()
1194 * @see wpdb::$field_types
1195 * @see wp_set_wpdb_vars()
1197 * @param string $table table name
1198 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1199 * @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.
1200 * 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.
1201 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1202 * @return int|false The number of rows affected, or false on error.
1204 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1205 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1207 $formats = $format = (array) $format;
1208 $fields = array_keys( $data );
1209 $formatted_fields = array();
1210 foreach ( $fields as $field ) {
1211 if ( !empty( $format ) )
1212 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1213 elseif ( isset( $this->field_types[$field] ) )
1214 $form = $this->field_types[$field];
1217 $formatted_fields[] = $form;
1219 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
1220 return $this->query( $this->prepare( $sql, $data ) );
1224 * Update a row in the table
1227 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1228 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1232 * @see wpdb::prepare()
1233 * @see wpdb::$field_types
1234 * @see wp_set_wpdb_vars()
1236 * @param string $table table name
1237 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1238 * @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".
1239 * @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.
1240 * 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.
1241 * @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.
1242 * @return int|false The number of rows updated, or false on error.
1244 function update( $table, $data, $where, $format = null, $where_format = null ) {
1245 if ( ! is_array( $data ) || ! is_array( $where ) )
1248 $formats = $format = (array) $format;
1249 $bits = $wheres = array();
1250 foreach ( (array) array_keys( $data ) as $field ) {
1251 if ( !empty( $format ) )
1252 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1253 elseif ( isset($this->field_types[$field]) )
1254 $form = $this->field_types[$field];
1257 $bits[] = "`$field` = {$form}";
1260 $where_formats = $where_format = (array) $where_format;
1261 foreach ( (array) array_keys( $where ) as $field ) {
1262 if ( !empty( $where_format ) )
1263 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1264 elseif ( isset( $this->field_types[$field] ) )
1265 $form = $this->field_types[$field];
1268 $wheres[] = "`$field` = {$form}";
1271 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1272 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1276 * Delete a row in the table
1279 * wpdb::delete( 'table', array( 'ID' => 1 ) )
1280 * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1284 * @see wpdb::prepare()
1285 * @see wpdb::$field_types
1286 * @see wp_set_wpdb_vars()
1288 * @param string $table table name
1289 * @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".
1290 * @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.
1291 * @return int|false The number of rows updated, or false on error.
1293 function delete( $table, $where, $where_format = null ) {
1294 if ( ! is_array( $where ) )
1297 $bits = $wheres = array();
1299 $where_formats = $where_format = (array) $where_format;
1301 foreach ( array_keys( $where ) as $field ) {
1302 if ( !empty( $where_format ) ) {
1303 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1304 } elseif ( isset( $this->field_types[ $field ] ) ) {
1305 $form = $this->field_types[ $field ];
1310 $wheres[] = "$field = $form";
1313 $sql = "DELETE FROM $table WHERE " . implode( ' AND ', $wheres );
1314 return $this->query( $this->prepare( $sql, $where ) );
1319 * Retrieve one variable from the database.
1321 * Executes a SQL query and returns the value from the SQL result.
1322 * 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.
1323 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1327 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1328 * @param int $x Optional. Column of value to return. Indexed from 0.
1329 * @param int $y Optional. Row of value to return. Indexed from 0.
1330 * @return string|null Database query result (as string), or null on failure
1332 function get_var( $query = null, $x = 0, $y = 0 ) {
1333 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1335 $this->query( $query );
1337 // Extract var out of cached results based x,y vals
1338 if ( !empty( $this->last_result[$y] ) ) {
1339 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1342 // If there is a value return it else return null
1343 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1347 * Retrieve one row from the database.
1349 * Executes a SQL query and returns the row from the SQL result.
1353 * @param string|null $query SQL query.
1354 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1355 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1356 * @param int $y Optional. Row to return. Indexed from 0.
1357 * @return mixed Database query result in format specified by $output or null on failure
1359 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1360 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1362 $this->query( $query );
1366 if ( !isset( $this->last_result[$y] ) )
1369 if ( $output == OBJECT ) {
1370 return $this->last_result[$y] ? $this->last_result[$y] : null;
1371 } elseif ( $output == ARRAY_A ) {
1372 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1373 } elseif ( $output == ARRAY_N ) {
1374 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1376 $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
1381 * Retrieve one column from the database.
1383 * Executes a SQL query and returns the column from the SQL result.
1384 * If the SQL result contains more than one column, this function returns the column specified.
1385 * If $query is null, this function returns the specified column from the previous SQL result.
1389 * @param string|null $query Optional. SQL query. Defaults to previous query.
1390 * @param int $x Optional. Column to return. Indexed from 0.
1391 * @return array Database query result. Array indexed from 0 by SQL result row number.
1393 function get_col( $query = null , $x = 0 ) {
1395 $this->query( $query );
1397 $new_array = array();
1398 // Extract the column values
1399 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1400 $new_array[$i] = $this->get_var( null, $x, $i );
1406 * Retrieve an entire SQL result set from the database (i.e., many rows)
1408 * Executes a SQL query and returns the entire SQL result.
1412 * @param string $query SQL query.
1413 * @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.
1414 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1415 * 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.
1416 * @return mixed Database query results
1418 function get_results( $query = null, $output = OBJECT ) {
1419 $this->func_call = "\$db->get_results(\"$query\", $output)";
1422 $this->query( $query );
1426 $new_array = array();
1427 if ( $output == OBJECT ) {
1428 // Return an integer-keyed array of row objects
1429 return $this->last_result;
1430 } elseif ( $output == OBJECT_K ) {
1431 // Return an array of row objects with keys from column 1
1432 // (Duplicates are discarded)
1433 foreach ( $this->last_result as $row ) {
1434 $var_by_ref = get_object_vars( $row );
1435 $key = array_shift( $var_by_ref );
1436 if ( ! isset( $new_array[ $key ] ) )
1437 $new_array[ $key ] = $row;
1440 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1441 // Return an integer-keyed array of...
1442 if ( $this->last_result ) {
1443 foreach( (array) $this->last_result as $row ) {
1444 if ( $output == ARRAY_N ) {
1445 // ...integer-keyed row arrays
1446 $new_array[] = array_values( get_object_vars( $row ) );
1448 // ...column name-keyed row arrays
1449 $new_array[] = get_object_vars( $row );
1459 * Retrieve column metadata from the last query.
1463 * @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
1464 * @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
1465 * @return mixed Column Results
1467 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1468 if ( $this->col_info ) {
1469 if ( $col_offset == -1 ) {
1471 $new_array = array();
1472 foreach( (array) $this->col_info as $col ) {
1473 $new_array[$i] = $col->{$info_type};
1478 return $this->col_info[$col_offset]->{$info_type};
1484 * Starts the timer, for debugging purposes.
1490 function timer_start() {
1491 $this->time_start = microtime( true );
1496 * Stops the debugging timer.
1500 * @return float Total time spent on the query, in seconds
1502 function timer_stop() {
1503 return ( microtime( true ) - $this->time_start );
1507 * Wraps errors in a nice header and footer and dies.
1509 * Will not die if wpdb::$show_errors is true
1513 * @param string $message The Error message
1514 * @param string $error_code Optional. A Computer readable string to identify the error.
1515 * @return false|void
1517 function bail( $message, $error_code = '500' ) {
1518 if ( !$this->show_errors ) {
1519 if ( class_exists( 'WP_Error' ) )
1520 $this->error = new WP_Error($error_code, $message);
1522 $this->error = $message;
1529 * Whether MySQL database is at least the required minimum version.
1533 * @uses $required_mysql_version
1537 function check_database_version() {
1538 global $wp_version, $required_mysql_version;
1539 // Make sure the server has the required MySQL version
1540 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1541 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1545 * Whether the database supports collation.
1547 * Called when WordPress is generating the table scheme.
1551 * @return bool True if collation is supported, false if version does not
1553 function supports_collation() {
1554 return $this->has_cap( 'collation' );
1558 * Determine if a database supports a particular feature
1561 * @see wpdb::db_version()
1563 * @param string $db_cap the feature
1566 function has_cap( $db_cap ) {
1567 $version = $this->db_version();
1569 switch ( strtolower( $db_cap ) ) {
1570 case 'collation' : // @since 2.5.0
1571 case 'group_concat' : // @since 2.7
1572 case 'subqueries' : // @since 2.7
1573 return version_compare( $version, '4.1', '>=' );
1574 case 'set_charset' :
1575 return version_compare($version, '5.0.7', '>=');
1582 * Retrieve the name of the function that called wpdb.
1584 * Searches up the list of functions until it reaches
1585 * the one that would most logically had called this method.
1589 * @return string The name of the calling function
1591 function get_caller() {
1592 return wp_debug_backtrace_summary( __CLASS__ );
1596 * The database version number.
1600 * @return false|string false on failure, version number on success
1602 function db_version() {
1603 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );