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 with your class. You can name it wpdb also, since
43 * this file will not be included, if the other file is
46 * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
49 * @subpackage Database
55 * Whether to show SQL/DB errors
61 var $show_errors = false;
64 * Whether to suppress errors during the DB bootstrapping.
70 var $suppress_errors = false;
73 * The last error during query.
75 * @see get_last_error()
83 * Amount of queries made
92 * Count of rows returned by previous query
101 * Count of affected rows by previous query
107 var $rows_affected = 0;
110 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
119 * Saved result of the last query made
128 * Results of the last query made
137 * Saved info on the table column
146 * Saved queries that were executed
155 * WordPress table prefix
157 * You can set this to have multiple WordPress installations
158 * in a single database. The second reason is for possible
159 * security precautions.
168 * Whether the database queries are ready to start executing.
177 * {@internal Missing Description}}
186 * {@internal Missing Description}}
195 * List of WordPress per-blog tables
199 * @see wpdb::tables()
202 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
203 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
206 * List of deprecated WordPress tables
208 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
212 * @see wpdb::tables()
215 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
218 * List of WordPress global tables
222 * @see wpdb::tables()
225 var $global_tables = array( 'users', 'usermeta' );
228 * List of Multisite global tables
232 * @see wpdb::tables()
235 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
236 'sitecategories', 'registration_log', 'blog_versions' );
239 * WordPress Comments table
248 * WordPress Comment Metadata table
257 * WordPress Links table
266 * WordPress Options table
275 * WordPress Post Metadata table
284 * WordPress Posts table
293 * WordPress Terms table
302 * WordPress Term Relationships table
308 var $term_relationships;
311 * WordPress Term Taxonomy table
320 * Global and Multisite tables
324 * WordPress User Metadata table
333 * WordPress Users table
342 * Multisite Blogs table
351 * Multisite Blog Versions table
360 * Multisite Registration Log table
366 var $registration_log;
369 * Multisite Signups table
378 * Multisite Sites table
387 * Multisite Sitewide Terms table
396 * Multisite Site Metadata table
405 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
407 * Keys are column names, values are format types: 'ID' => '%d'
410 * @see wpdb:prepare()
413 * @see wp_set_wpdb_vars()
417 var $field_types = array();
420 * Database table columns charset
429 * Database table columns collate
438 * Whether to use mysql_real_escape_string
444 var $real_escape = false;
456 * A textual description of the last query/get_row/get_var call
465 * Connects to the database server and selects a database
467 * PHP4 compatibility layer for calling the PHP5 constructor.
469 * @uses wpdb::__construct() Passes parameters and returns result
472 * @param string $dbuser MySQL database user
473 * @param string $dbpassword MySQL database password
474 * @param string $dbname MySQL database name
475 * @param string $dbhost MySQL database host
477 function wpdb( $dbuser, $dbpassword, $dbname, $dbhost ) {
478 return $this->__construct( $dbuser, $dbpassword, $dbname, $dbhost );
482 * Connects to the database server and selects a database
484 * PHP5 style constructor for compatibility with PHP5. Does
485 * the actual setting up of the class properties and connection
488 * @link http://core.trac.wordpress.org/ticket/3354
491 * @param string $dbuser MySQL database user
492 * @param string $dbpassword MySQL database password
493 * @param string $dbname MySQL database name
494 * @param string $dbhost MySQL database host
496 function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
497 register_shutdown_function( array( &$this, '__destruct' ) );
500 $this->show_errors();
502 $this->init_charset();
504 $this->dbuser = $dbuser;
505 $this->dbpassword = $dbpassword;
506 $this->dbname = $dbname;
507 $this->dbhost = $dbhost;
513 * PHP5 style destructor and will run when database object is destroyed.
515 * @see wpdb::__construct()
519 function __destruct() {
524 * Set $this->charset and $this->collate
528 function init_charset() {
529 if ( function_exists('is_multisite') && is_multisite() ) {
530 $this->charset = 'utf8';
531 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
532 $this->collate = DB_COLLATE;
534 $this->collate = 'utf8_general_ci';
535 } elseif ( defined( 'DB_COLLATE' ) ) {
536 $this->collate = DB_COLLATE;
539 if ( defined( 'DB_CHARSET' ) )
540 $this->charset = DB_CHARSET;
544 * Sets the connection's character set.
548 * @param resource $dbh The resource given by mysql_connect
549 * @param string $charset The character set (optional)
550 * @param string $collate The collation (optional)
552 function set_charset($dbh, $charset = null, $collate = null) {
553 if ( !isset($charset) )
554 $charset = $this->charset;
555 if ( !isset($collate) )
556 $collate = $this->collate;
557 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
558 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
559 mysql_set_charset( $charset, $dbh );
560 $this->real_escape = true;
562 $query = $this->prepare( 'SET NAMES %s', $charset );
563 if ( ! empty( $collate ) )
564 $query .= $this->prepare( ' COLLATE %s', $collate );
565 mysql_query( $query, $dbh );
571 * Sets the table prefix for the WordPress tables.
575 * @param string $prefix Alphanumeric name for the new prefix.
576 * @return string|WP_Error Old prefix or WP_Error on error
578 function set_prefix( $prefix, $set_table_names = true ) {
580 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
581 return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
583 $old_prefix = is_multisite() ? '' : $prefix;
585 if ( isset( $this->base_prefix ) )
586 $old_prefix = $this->base_prefix;
588 $this->base_prefix = $prefix;
590 if ( $set_table_names ) {
591 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
592 $this->$table = $prefixed_table;
594 if ( is_multisite() && empty( $this->blogid ) )
597 $this->prefix = $this->get_blog_prefix();
599 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
600 $this->$table = $prefixed_table;
602 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
603 $this->$table = $prefixed_table;
613 * @param int $blog_id
614 * @param int $site_id Optional.
615 * @return string previous blog id
617 function set_blog_id( $blog_id, $site_id = 0 ) {
618 if ( ! empty( $site_id ) )
619 $this->siteid = $site_id;
621 $old_blog_id = $this->blogid;
622 $this->blogid = $blog_id;
624 $this->prefix = $this->get_blog_prefix();
626 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
627 $this->$table = $prefixed_table;
629 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
630 $this->$table = $prefixed_table;
638 * @uses is_multisite()
640 * @param int $blog_id Optional.
641 * @return string Blog prefix.
643 function get_blog_prefix( $blog_id = null ) {
644 if ( is_multisite() ) {
645 if ( null === $blog_id )
646 $blog_id = $this->blogid;
647 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
648 return $this->base_prefix;
650 return $this->base_prefix . $blog_id . '_';
652 return $this->base_prefix;
657 * Returns an array of WordPress tables.
659 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
660 * override the WordPress users and usersmeta tables that would otherwise
661 * be determined by the prefix.
663 * The scope argument can take one of the following:
665 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
666 * 'blog' - returns the blog-level tables for the queried blog.
667 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
668 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
669 * 'old' - returns tables which are deprecated.
672 * @uses wpdb::$tables
673 * @uses wpdb::$old_tables
674 * @uses wpdb::$global_tables
675 * @uses wpdb::$ms_global_tables
676 * @uses is_multisite()
678 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
679 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
680 * prefix is requested, then the custom users and usermeta tables will be mapped.
681 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
682 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
684 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
687 $tables = array_merge( $this->global_tables, $this->tables );
688 if ( is_multisite() )
689 $tables = array_merge( $tables, $this->ms_global_tables );
692 $tables = $this->tables;
695 $tables = $this->global_tables;
696 if ( is_multisite() )
697 $tables = array_merge( $tables, $this->ms_global_tables );
700 $tables = $this->ms_global_tables;
703 $tables = $this->old_tables;
712 $blog_id = $this->blogid;
713 $blog_prefix = $this->get_blog_prefix( $blog_id );
714 $base_prefix = $this->base_prefix;
715 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
716 foreach ( $tables as $k => $table ) {
717 if ( in_array( $table, $global_tables ) )
718 $tables[ $table ] = $base_prefix . $table;
720 $tables[ $table ] = $blog_prefix . $table;
721 unset( $tables[ $k ] );
724 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
725 $tables['users'] = CUSTOM_USER_TABLE;
727 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
728 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
735 * Selects a database using the current database connection.
737 * The database name will be changed based on the current database
738 * connection. On failure, the execution will bail and display an DB error.
742 * @param string $db MySQL database name
743 * @param resource $dbh Optional link identifier.
744 * @return null Always null.
746 function select( $db, $dbh = null) {
750 if ( !@mysql_select_db( $db, $dbh ) ) {
751 $this->ready = false;
752 $this->bail( sprintf( /*WP_I18N_DB_SELECT_DB*/'<h1>Can’t select database</h1>
753 <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>
755 <li>Are you sure it exists?</li>
756 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
757 <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>
759 <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>'/*/WP_I18N_DB_SELECT_DB*/, $db, $this->dbuser ), 'db_select_fail' );
765 * Weak escape, using addslashes()
771 * @param string $string
774 function _weak_escape( $string ) {
775 return addslashes( $string );
779 * Real escape, using mysql_real_escape_string() or addslashes()
781 * @see mysql_real_escape_string()
786 * @param string $string to escape
787 * @return string escaped
789 function _real_escape( $string ) {
790 if ( $this->dbh && $this->real_escape )
791 return mysql_real_escape_string( $string, $this->dbh );
793 return addslashes( $string );
797 * Escape data. Works on arrays.
799 * @uses wpdb::_escape()
800 * @uses wpdb::_real_escape()
804 * @param string|array $data
805 * @return string|array escaped
807 function _escape( $data ) {
808 if ( is_array( $data ) ) {
809 foreach ( (array) $data as $k => $v ) {
811 $data[$k] = $this->_escape( $v );
813 $data[$k] = $this->_real_escape( $v );
816 $data = $this->_real_escape( $data );
823 * Escapes content for insertion into the database using addslashes(), for security.
828 * @param string|array $data to escape
829 * @return string|array escaped as query safe string
831 function escape( $data ) {
832 if ( is_array( $data ) ) {
833 foreach ( (array) $data as $k => $v ) {
834 if ( is_array( $v ) )
835 $data[$k] = $this->escape( $v );
837 $data[$k] = $this->_weak_escape( $v );
840 $data = $this->_weak_escape( $data );
847 * Escapes content by reference for insertion into the database, for security
849 * @uses wpdb::_real_escape()
851 * @param string $string to escape
854 function escape_by_ref( &$string ) {
855 $string = $this->_real_escape( $string );
859 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
861 * The following directives can be used in the query format string:
862 * %d (decimal number)
864 * %% (literal percentage sign - no argument needed)
866 * Both %d and %s are to be left unquoted in the query string and they need an argument passed for them.
867 * Literals (%) as parts of the query must be properly written as %%.
869 * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
870 * Does not support sign, padding, alignment, width or precision specifiers.
871 * Does not support argument numbering/swapping.
873 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
875 * Both %d and %s should be left unquoted in the query string.
878 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
879 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
882 * @link http://php.net/sprintf Description of syntax.
885 * @param string $query Query statement with sprintf()-like placeholders
886 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
887 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
888 * being called like {@link http://php.net/sprintf sprintf()}.
889 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
890 * {@link http://php.net/sprintf sprintf()}.
891 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
892 * if there was something to prepare
894 function prepare( $query = null ) { // ( $query, *$args )
895 if ( is_null( $query ) )
898 $args = func_get_args();
899 array_shift( $args );
900 // If args were passed as an array (as in vsprintf), move them up
901 if ( isset( $args[0] ) && is_array($args[0]) )
903 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
904 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
905 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
906 array_walk( $args, array( &$this, 'escape_by_ref' ) );
907 return @vsprintf( $query, $args );
911 * Print SQL/DB error.
914 * @global array $EZSQL_ERROR Stores error information of query and error string
916 * @param string $str The error to display
917 * @return bool False if the showing of errors is disabled.
919 function print_error( $str = '' ) {
923 $str = mysql_error( $this->dbh );
924 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
926 if ( $this->suppress_errors )
929 if ( $caller = $this->get_caller() )
930 $error_str = sprintf( /*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress database error %1$s for query %2$s made by %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller );
932 $error_str = sprintf( /*WP_I18N_DB_QUERY_ERROR*/'WordPress database error %1$s for query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query );
934 if ( function_exists( 'error_log' )
935 && ( $log_file = @ini_get( 'error_log' ) )
936 && ( 'syslog' == $log_file || @is_writable( $log_file ) )
938 @error_log( $error_str );
940 // Are we showing errors?
941 if ( ! $this->show_errors )
944 // If there is an error then take note of it
945 if ( is_multisite() ) {
946 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
947 if ( defined( 'ERRORLOGFILE' ) )
948 error_log( $msg, 3, ERRORLOGFILE );
949 if ( defined( 'DIEONDBERROR' ) )
952 $str = htmlspecialchars( $str, ENT_QUOTES );
953 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
955 print "<div id='error'>
956 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
957 <code>$query</code></p>
963 * Enables showing of database errors.
965 * This function should be used only to enable showing of errors.
966 * wpdb::hide_errors() should be used instead for hiding of errors. However,
967 * this function can be used to enable and disable showing of database
971 * @see wpdb::hide_errors()
973 * @param bool $show Whether to show or hide errors
974 * @return bool Old value for showing errors.
976 function show_errors( $show = true ) {
977 $errors = $this->show_errors;
978 $this->show_errors = $show;
983 * Disables showing of database errors.
985 * By default database errors are not shown.
988 * @see wpdb::show_errors()
990 * @return bool Whether showing of errors was active
992 function hide_errors() {
993 $show = $this->show_errors;
994 $this->show_errors = false;
999 * Whether to suppress database errors.
1001 * By default database errors are suppressed, with a simple
1002 * call to this function they can be enabled.
1005 * @see wpdb::hide_errors()
1006 * @param bool $suppress Optional. New value. Defaults to true.
1007 * @return bool Old value
1009 function suppress_errors( $suppress = true ) {
1010 $errors = $this->suppress_errors;
1011 $this->suppress_errors = (bool) $suppress;
1016 * Kill cached query results.
1022 $this->last_result = array();
1023 $this->col_info = null;
1024 $this->last_query = null;
1028 * Connect to and select database
1032 function db_connect() {
1033 global $db_list, $global_db_list;
1036 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1038 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1041 if ( !$this->dbh ) {
1042 $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/"
1043 <h1>Error establishing a database connection</h1>
1044 <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>
1046 <li>Are you sure you have the correct username and password?</li>
1047 <li>Are you sure that you have typed the correct hostname?</li>
1048 <li>Are you sure that the database server is running?</li>
1050 <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>
1051 "/*/WP_I18N_DB_CONN_ERROR*/, $this->dbhost ), 'db_connect_fail' );
1056 $this->set_charset( $this->dbh );
1058 $this->ready = true;
1060 $this->select( $this->dbname, $this->dbh );
1064 * Perform a MySQL database query, using current database connection.
1066 * More information can be found on the codex page.
1070 * @param string $query Database query
1071 * @return int|false Number of rows affected/selected or false on error
1073 function query( $query ) {
1074 if ( ! $this->ready )
1077 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1078 if ( function_exists( 'apply_filters' ) )
1079 $query = apply_filters( 'query', $query );
1084 // Log how the function was called
1085 $this->func_call = "\$db->query(\"$query\")";
1087 // Keep track of the last query for debug..
1088 $this->last_query = $query;
1090 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1091 $this->timer_start();
1093 $this->result = @mysql_query( $query, $this->dbh );
1094 $this->num_queries++;
1096 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1097 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1099 // If there is an error then take note of it..
1100 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1101 $this->print_error();
1105 if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) {
1106 $this->rows_affected = mysql_affected_rows( $this->dbh );
1107 // Take note of the insert_id
1108 if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) {
1109 $this->insert_id = mysql_insert_id($this->dbh);
1111 // Return number of rows affected
1112 $return_val = $this->rows_affected;
1115 while ( $i < @mysql_num_fields( $this->result ) ) {
1116 $this->col_info[$i] = @mysql_fetch_field( $this->result );
1120 while ( $row = @mysql_fetch_object( $this->result ) ) {
1121 $this->last_result[$num_rows] = $row;
1125 @mysql_free_result( $this->result );
1127 // Log number of rows the query returned
1128 // and return number of rows selected
1129 $this->num_rows = $num_rows;
1130 $return_val = $num_rows;
1137 * Insert a row into a table.
1140 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1141 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1145 * @see wpdb::prepare()
1146 * @see wpdb::$field_types
1147 * @see wp_set_wpdb_vars()
1149 * @param string $table table name
1150 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1151 * @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.
1152 * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1153 * @return int|false The number of rows inserted, or false on error.
1155 function insert( $table, $data, $format = null ) {
1156 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1160 * Replace a row into a table.
1163 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1164 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1168 * @see wpdb::prepare()
1169 * @see wpdb::$field_types
1170 * @see wp_set_wpdb_vars()
1172 * @param string $table table name
1173 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1174 * @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.
1175 * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1176 * @return int|false The number of rows affected, or false on error.
1178 function replace( $table, $data, $format = null ) {
1179 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1183 * Helper function for insert and replace.
1185 * Runs an insert or replace query based on $type argument.
1189 * @see wpdb::prepare()
1190 * @see wpdb::$field_types
1191 * @see wp_set_wpdb_vars()
1193 * @param string $table table name
1194 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1195 * @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.
1196 * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1197 * @return int|false The number of rows affected, or false on error.
1199 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1200 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1202 $formats = $format = (array) $format;
1203 $fields = array_keys( $data );
1204 $formatted_fields = array();
1205 foreach ( $fields as $field ) {
1206 if ( !empty( $format ) )
1207 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1208 elseif ( isset( $this->field_types[$field] ) )
1209 $form = $this->field_types[$field];
1212 $formatted_fields[] = $form;
1214 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
1215 return $this->query( $this->prepare( $sql, $data ) );
1219 * Update a row in the table
1222 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1223 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1227 * @see wpdb::prepare()
1228 * @see wpdb::$field_types
1229 * @see wp_set_wpdb_vars()
1231 * @param string $table table name
1232 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1233 * @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".
1234 * @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.
1235 * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1236 * @param array|string $format_where 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', '%s' (decimal number, string). If omitted, all values in $where will be treated as strings.
1237 * @return int|false The number of rows updated, or false on error.
1239 function update( $table, $data, $where, $format = null, $where_format = null ) {
1240 if ( ! is_array( $data ) || ! is_array( $where ) )
1243 $formats = $format = (array) $format;
1244 $bits = $wheres = array();
1245 foreach ( (array) array_keys( $data ) as $field ) {
1246 if ( !empty( $format ) )
1247 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1248 elseif ( isset($this->field_types[$field]) )
1249 $form = $this->field_types[$field];
1252 $bits[] = "`$field` = {$form}";
1255 $where_formats = $where_format = (array) $where_format;
1256 foreach ( (array) array_keys( $where ) as $field ) {
1257 if ( !empty( $where_format ) )
1258 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1259 elseif ( isset( $this->field_types[$field] ) )
1260 $form = $this->field_types[$field];
1263 $wheres[] = "`$field` = {$form}";
1266 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1267 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1271 * Retrieve one variable from the database.
1273 * Executes a SQL query and returns the value from the SQL result.
1274 * 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.
1275 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1279 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1280 * @param int $x Optional. Column of value to return. Indexed from 0.
1281 * @param int $y Optional. Row of value to return. Indexed from 0.
1282 * @return string|null Database query result (as string), or null on failure
1284 function get_var( $query = null, $x = 0, $y = 0 ) {
1285 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1287 $this->query( $query );
1289 // Extract var out of cached results based x,y vals
1290 if ( !empty( $this->last_result[$y] ) ) {
1291 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1294 // If there is a value return it else return null
1295 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1299 * Retrieve one row from the database.
1301 * Executes a SQL query and returns the row from the SQL result.
1305 * @param string|null $query SQL query.
1306 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1307 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1308 * @param int $y Optional. Row to return. Indexed from 0.
1309 * @return mixed Database query result in format specifed by $output or null on failure
1311 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1312 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1314 $this->query( $query );
1318 if ( !isset( $this->last_result[$y] ) )
1321 if ( $output == OBJECT ) {
1322 return $this->last_result[$y] ? $this->last_result[$y] : null;
1323 } elseif ( $output == ARRAY_A ) {
1324 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1325 } elseif ( $output == ARRAY_N ) {
1326 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1328 $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/WP_I18N_DB_GETROW_ERROR*/);
1333 * Retrieve one column from the database.
1335 * Executes a SQL query and returns the column from the SQL result.
1336 * If the SQL result contains more than one column, this function returns the column specified.
1337 * If $query is null, this function returns the specified column from the previous SQL result.
1341 * @param string|null $query Optional. SQL query. Defaults to previous query.
1342 * @param int $x Optional. Column to return. Indexed from 0.
1343 * @return array Database query result. Array indexed from 0 by SQL result row number.
1345 function get_col( $query = null , $x = 0 ) {
1347 $this->query( $query );
1349 $new_array = array();
1350 // Extract the column values
1351 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1352 $new_array[$i] = $this->get_var( null, $x, $i );
1358 * Retrieve an entire SQL result set from the database (i.e., many rows)
1360 * Executes a SQL query and returns the entire SQL result.
1364 * @param string $query SQL query.
1365 * @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.
1366 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1367 * 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.
1368 * @return mixed Database query results
1370 function get_results( $query = null, $output = OBJECT ) {
1371 $this->func_call = "\$db->get_results(\"$query\", $output)";
1374 $this->query( $query );
1378 $new_array = array();
1379 if ( $output == OBJECT ) {
1380 // Return an integer-keyed array of row objects
1381 return $this->last_result;
1382 } elseif ( $output == OBJECT_K ) {
1383 // Return an array of row objects with keys from column 1
1384 // (Duplicates are discarded)
1385 foreach ( $this->last_result as $row ) {
1386 $key = array_shift( $var_by_ref = get_object_vars( $row ) );
1387 if ( ! isset( $new_array[ $key ] ) )
1388 $new_array[ $key ] = $row;
1391 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1392 // Return an integer-keyed array of...
1393 if ( $this->last_result ) {
1394 foreach( (array) $this->last_result as $row ) {
1395 if ( $output == ARRAY_N ) {
1396 // ...integer-keyed row arrays
1397 $new_array[] = array_values( get_object_vars( $row ) );
1399 // ...column name-keyed row arrays
1400 $new_array[] = get_object_vars( $row );
1410 * Retrieve column metadata from the last query.
1414 * @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
1415 * @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
1416 * @return mixed Column Results
1418 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1419 if ( $this->col_info ) {
1420 if ( $col_offset == -1 ) {
1422 $new_array = array();
1423 foreach( (array) $this->col_info as $col ) {
1424 $new_array[$i] = $col->{$info_type};
1429 return $this->col_info[$col_offset]->{$info_type};
1435 * Starts the timer, for debugging purposes.
1441 function timer_start() {
1442 $mtime = explode( ' ', microtime() );
1443 $this->time_start = $mtime[1] + $mtime[0];
1448 * Stops the debugging timer.
1452 * @return int Total time spent on the query, in milliseconds
1454 function timer_stop() {
1455 $mtime = explode( ' ', microtime() );
1456 $time_end = $mtime[1] + $mtime[0];
1457 $time_total = $time_end - $this->time_start;
1462 * Wraps errors in a nice header and footer and dies.
1464 * Will not die if wpdb::$show_errors is true
1468 * @param string $message The Error message
1469 * @param string $error_code Optional. A Computer readable string to identify the error.
1470 * @return false|void
1472 function bail( $message, $error_code = '500' ) {
1473 if ( !$this->show_errors ) {
1474 if ( class_exists( 'WP_Error' ) )
1475 $this->error = new WP_Error($error_code, $message);
1477 $this->error = $message;
1484 * Whether MySQL database is at least the required minimum version.
1488 * @uses $required_mysql_version
1492 function check_database_version() {
1493 global $wp_version, $required_mysql_version;
1494 // Make sure the server has the required MySQL version
1495 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1496 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1500 * Whether the database supports collation.
1502 * Called when WordPress is generating the table scheme.
1506 * @return bool True if collation is supported, false if version does not
1508 function supports_collation() {
1509 return $this->has_cap( 'collation' );
1513 * Determine if a database supports a particular feature
1516 * @see wpdb::db_version()
1518 * @param string $db_cap the feature
1521 function has_cap( $db_cap ) {
1522 $version = $this->db_version();
1524 switch ( strtolower( $db_cap ) ) {
1525 case 'collation' : // @since 2.5.0
1526 case 'group_concat' : // @since 2.7
1527 case 'subqueries' : // @since 2.7
1528 return version_compare( $version, '4.1', '>=' );
1529 case 'set_charset' :
1530 return version_compare($version, '5.0.7', '>=');
1537 * Retrieve the name of the function that called wpdb.
1539 * Searches up the list of functions until it reaches
1540 * the one that would most logically had called this method.
1544 * @return string The name of the calling function
1546 function get_caller() {
1547 $trace = array_reverse( debug_backtrace() );
1550 foreach ( $trace as $call ) {
1551 if ( isset( $call['class'] ) && __CLASS__ == $call['class'] )
1552 continue; // Filter out wpdb calls.
1553 $caller[] = isset( $call['class'] ) ? "{$call['class']}->{$call['function']}" : $call['function'];
1556 return join( ', ', $caller );
1560 * The database version number.
1564 * @return false|string false on failure, version number on success
1566 function db_version() {
1567 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );