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
56 * Whether to show SQL/DB errors
62 var $show_errors = false;
65 * Whether to suppress errors during the DB bootstrapping.
71 var $suppress_errors = false;
74 * The last error during query.
76 * @see get_last_error()
84 * Amount of queries made
93 * Count of rows returned by previous query
102 * Count of affected rows by previous query
108 var $rows_affected = 0;
111 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
120 * Saved result of the last query made
129 * Results of the last query made
138 * Saved info on the table column
147 * Saved queries that were executed
156 * WordPress table prefix
158 * You can set this to have multiple WordPress installations
159 * in a single database. The second reason is for possible
160 * security precautions.
169 * Whether the database queries are ready to start executing.
178 * {@internal Missing Description}}
187 * {@internal Missing Description}}
196 * List of WordPress per-blog tables
200 * @see wpdb::tables()
203 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
204 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
207 * List of deprecated WordPress tables
209 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
213 * @see wpdb::tables()
216 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
219 * List of WordPress global tables
223 * @see wpdb::tables()
226 var $global_tables = array( 'users', 'usermeta' );
229 * List of Multisite global tables
233 * @see wpdb::tables()
236 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
237 'sitecategories', 'registration_log', 'blog_versions' );
240 * WordPress Comments table
249 * WordPress Comment Metadata table
258 * WordPress Links table
267 * WordPress Options table
276 * WordPress Post Metadata table
285 * WordPress Posts table
294 * WordPress Terms table
303 * WordPress Term Relationships table
309 var $term_relationships;
312 * WordPress Term Taxonomy table
321 * Global and Multisite tables
325 * WordPress User Metadata table
334 * WordPress Users table
343 * Multisite Blogs table
352 * Multisite Blog Versions table
361 * Multisite Registration Log table
367 var $registration_log;
370 * Multisite Signups table
379 * Multisite Sites table
388 * Multisite Sitewide Terms table
397 * Multisite Site Metadata table
406 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
408 * Keys are column names, values are format types: 'ID' => '%d'
411 * @see wpdb:prepare()
414 * @see wp_set_wpdb_vars()
418 var $field_types = array();
421 * Database table columns charset
430 * Database table columns collate
439 * Whether to use mysql_real_escape_string
445 var $real_escape = false;
457 * A textual description of the last query/get_row/get_var call
466 * Connects to the database server and selects a database
468 * PHP4 compatibility layer for calling the PHP5 constructor.
470 * @uses wpdb::__construct() Passes parameters and returns result
473 * @param string $dbuser MySQL database user
474 * @param string $dbpassword MySQL database password
475 * @param string $dbname MySQL database name
476 * @param string $dbhost MySQL database host
478 function wpdb( $dbuser, $dbpassword, $dbname, $dbhost ) {
479 if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB )
481 return $this->__construct( $dbuser, $dbpassword, $dbname, $dbhost );
485 * Connects to the database server and selects a database
487 * PHP5 style constructor for compatibility with PHP5. Does
488 * the actual setting up of the class properties and connection
491 * @link http://core.trac.wordpress.org/ticket/3354
494 * @param string $dbuser MySQL database user
495 * @param string $dbpassword MySQL database password
496 * @param string $dbname MySQL database name
497 * @param string $dbhost MySQL database host
499 function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
500 register_shutdown_function( array( &$this, '__destruct' ) );
503 $this->show_errors();
505 if ( is_multisite() ) {
506 $this->charset = 'utf8';
507 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
508 $this->collate = DB_COLLATE;
510 $this->collate = 'utf8_general_ci';
511 } elseif ( defined( 'DB_COLLATE' ) ) {
512 $this->collate = DB_COLLATE;
515 if ( defined( 'DB_CHARSET' ) )
516 $this->charset = DB_CHARSET;
518 $this->dbuser = $dbuser;
520 $this->dbh = @mysql_connect( $dbhost, $dbuser, $dbpassword, true );
522 $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/"
523 <h1>Error establishing a database connection</h1>
524 <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>
526 <li>Are you sure you have the correct username and password?</li>
527 <li>Are you sure that you have typed the correct hostname?</li>
528 <li>Are you sure that the database server is running?</li>
530 <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>
531 "/*/WP_I18N_DB_CONN_ERROR*/, $dbhost ), 'db_connect_fail' );
537 if ( $this->has_cap( 'collation' ) && !empty( $this->charset ) ) {
538 if ( function_exists( 'mysql_set_charset' ) ) {
539 mysql_set_charset( $this->charset, $this->dbh );
540 $this->real_escape = true;
542 $query = $this->prepare( 'SET NAMES %s', $this->charset );
543 if ( ! empty( $this->collate ) )
544 $query .= $this->prepare( ' COLLATE %s', $this->collate );
545 $this->query( $query );
549 $this->select( $dbname, $this->dbh );
553 * PHP5 style destructor and will run when database object is destroyed.
555 * @see wpdb::__construct()
559 function __destruct() {
564 * Sets the table prefix for the WordPress tables.
568 * @param string $prefix Alphanumeric name for the new prefix.
569 * @return string|WP_Error Old prefix or WP_Error on error
571 function set_prefix( $prefix, $set_table_names = true ) {
573 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
574 return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
576 $old_prefix = is_multisite() ? '' : $prefix;
578 if ( isset( $this->base_prefix ) )
579 $old_prefix = $this->base_prefix;
581 $this->base_prefix = $prefix;
583 if ( $set_table_names ) {
584 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
585 $this->$table = $prefixed_table;
587 if ( is_multisite() && empty( $this->blogid ) )
590 $this->prefix = $this->get_blog_prefix();
592 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
593 $this->$table = $prefixed_table;
595 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
596 $this->$table = $prefixed_table;
606 * @param int $blog_id
607 * @param int $site_id Optional.
608 * @return string previous blog id
610 function set_blog_id( $blog_id, $site_id = 0 ) {
611 if ( ! empty( $site_id ) )
612 $this->siteid = $site_id;
614 $old_blog_id = $this->blogid;
615 $this->blogid = $blog_id;
617 $this->prefix = $this->get_blog_prefix();
619 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
620 $this->$table = $prefixed_table;
622 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
623 $this->$table = $prefixed_table;
631 * @uses is_multisite()
633 * @param int $blog_id Optional.
634 * @return string Blog prefix.
636 function get_blog_prefix( $blog_id = null ) {
637 if ( is_multisite() ) {
638 if ( null === $blog_id )
639 $blog_id = $this->blogid;
640 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
641 return $this->base_prefix;
643 return $this->base_prefix . $blog_id . '_';
645 return $this->base_prefix;
650 * Returns an array of WordPress tables.
652 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
653 * override the WordPress users and usersmeta tables that would otherwise
654 * be determined by the prefix.
656 * The scope argument can take one of the following:
658 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
659 * 'blog' - returns the blog-level tables for the queried blog.
660 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
661 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
662 * 'old' - returns tables which are deprecated.
665 * @uses wpdb::$tables
666 * @uses wpdb::$old_tables
667 * @uses wpdb::$global_tables
668 * @uses wpdb::$ms_global_tables
669 * @uses is_multisite()
671 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
672 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
673 * prefix is requested, then the custom users and usermeta tables will be mapped.
674 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
675 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
677 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
680 $tables = array_merge( $this->global_tables, $this->tables );
681 if ( is_multisite() )
682 $tables = array_merge( $tables, $this->ms_global_tables );
685 $tables = $this->tables;
688 $tables = $this->global_tables;
689 if ( is_multisite() )
690 $tables = array_merge( $tables, $this->ms_global_tables );
693 $tables = $this->ms_global_tables;
696 $tables = $this->old_tables;
705 $blog_id = $this->blogid;
706 $blog_prefix = $this->get_blog_prefix( $blog_id );
707 $base_prefix = $this->base_prefix;
708 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
709 foreach ( $tables as $k => $table ) {
710 if ( in_array( $table, $global_tables ) )
711 $tables[ $table ] = $base_prefix . $table;
713 $tables[ $table ] = $blog_prefix . $table;
714 unset( $tables[ $k ] );
717 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
718 $tables['users'] = CUSTOM_USER_TABLE;
720 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
721 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
728 * Selects a database using the current database connection.
730 * The database name will be changed based on the current database
731 * connection. On failure, the execution will bail and display an DB error.
735 * @param string $db MySQL database name
736 * @param resource $dbh Optional link identifier.
737 * @return null Always null.
739 function select( $db, $dbh = null) {
743 if ( !@mysql_select_db( $db, $dbh ) ) {
744 $this->ready = false;
745 $this->bail( sprintf( /*WP_I18N_DB_SELECT_DB*/'
746 <h1>Can’t select database</h1>
747 <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>
749 <li>Are you sure it exists?</li>
750 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
751 <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>
753 <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' );
759 * Weak escape, using addslashes()
765 * @param string $string
768 function _weak_escape( $string ) {
769 return addslashes( $string );
773 * Real escape, using mysql_real_escape_string() or addslashes()
775 * @see mysql_real_escape_string()
780 * @param string $string to escape
781 * @return string escaped
783 function _real_escape( $string ) {
784 if ( $this->dbh && $this->real_escape )
785 return mysql_real_escape_string( $string, $this->dbh );
787 return addslashes( $string );
791 * Escape data. Works on arrays.
793 * @uses wpdb::_escape()
794 * @uses wpdb::_real_escape()
798 * @param string|array $data
799 * @return string|array escaped
801 function _escape( $data ) {
802 if ( is_array( $data ) ) {
803 foreach ( (array) $data as $k => $v ) {
805 $data[$k] = $this->_escape( $v );
807 $data[$k] = $this->_real_escape( $v );
810 $data = $this->_real_escape( $data );
817 * Escapes content for insertion into the database using addslashes(), for security.
822 * @param string|array $data to escape
823 * @return string|array escaped as query safe string
825 function escape( $data ) {
826 if ( is_array( $data ) ) {
827 foreach ( (array) $data as $k => $v ) {
828 if ( is_array( $v ) )
829 $data[$k] = $this->escape( $v );
831 $data[$k] = $this->_weak_escape( $v );
834 $data = $this->_weak_escape( $data );
841 * Escapes content by reference for insertion into the database, for security
843 * @uses wpdb::_real_escape()
845 * @param string $string to escape
848 function escape_by_ref( &$string ) {
849 $string = $this->_real_escape( $string );
853 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
855 * The following directives can be used in the query format string:
856 * %d (decimal number)
858 * %% (literal percentage sign - no argument needed)
860 * Both %d and %s are to be left unquoted in the query string and they need an argument passed for them.
861 * Literals (%) as parts of the query must be properly written as %%.
863 * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
864 * Does not support sign, padding, alignment, width or precision specifiers.
865 * Does not support argument numbering/swapping.
867 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
869 * Both %d and %s should be left unquoted in the query string.
872 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
873 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
876 * @link http://php.net/sprintf Description of syntax.
879 * @param string $query Query statement with sprintf()-like placeholders
880 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
881 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
882 * being called like {@link http://php.net/sprintf sprintf()}.
883 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
884 * {@link http://php.net/sprintf sprintf()}.
885 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
886 * if there was something to prepare
888 function prepare( $query = null ) { // ( $query, *$args )
889 if ( is_null( $query ) )
892 $args = func_get_args();
893 array_shift( $args );
894 // If args were passed as an array (as in vsprintf), move them up
895 if ( isset( $args[0] ) && is_array($args[0]) )
897 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
898 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
899 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
900 array_walk( $args, array( &$this, 'escape_by_ref' ) );
901 return @vsprintf( $query, $args );
905 * Print SQL/DB error.
908 * @global array $EZSQL_ERROR Stores error information of query and error string
910 * @param string $str The error to display
911 * @return bool False if the showing of errors is disabled.
913 function print_error( $str = '' ) {
917 $str = mysql_error( $this->dbh );
918 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
920 if ( $this->suppress_errors )
923 if ( $caller = $this->get_caller() )
924 $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 );
926 $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 );
928 if ( function_exists( 'error_log' )
929 && ( $log_file = @ini_get( 'error_log' ) )
930 && ( 'syslog' == $log_file || @is_writable( $log_file ) )
932 @error_log( $error_str );
934 // Are we showing errors?
935 if ( ! $this->show_errors )
938 // If there is an error then take note of it
939 if ( is_multisite() ) {
940 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
941 if ( defined( 'ERRORLOGFILE' ) )
942 error_log( $msg, 3, ERRORLOGFILE );
943 if ( defined( 'DIEONDBERROR' ) )
946 $str = htmlspecialchars( $str, ENT_QUOTES );
947 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
949 print "<div id='error'>
950 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
951 <code>$query</code></p>
957 * Enables showing of database errors.
959 * This function should be used only to enable showing of errors.
960 * wpdb::hide_errors() should be used instead for hiding of errors. However,
961 * this function can be used to enable and disable showing of database
965 * @see wpdb::hide_errors()
967 * @param bool $show Whether to show or hide errors
968 * @return bool Old value for showing errors.
970 function show_errors( $show = true ) {
971 $errors = $this->show_errors;
972 $this->show_errors = $show;
977 * Disables showing of database errors.
979 * By default database errors are not shown.
982 * @see wpdb::show_errors()
984 * @return bool Whether showing of errors was active
986 function hide_errors() {
987 $show = $this->show_errors;
988 $this->show_errors = false;
993 * Whether to suppress database errors.
995 * By default database errors are suppressed, with a simple
996 * call to this function they can be enabled.
999 * @see wpdb::hide_errors()
1000 * @param bool $suppress Optional. New value. Defaults to true.
1001 * @return bool Old value
1003 function suppress_errors( $suppress = true ) {
1004 $errors = $this->suppress_errors;
1005 $this->suppress_errors = (bool) $suppress;
1010 * Kill cached query results.
1016 $this->last_result = array();
1017 $this->col_info = null;
1018 $this->last_query = null;
1021 function db_connect( $query = "SELECT" ) {
1022 global $db_list, $global_db_list;
1023 if ( ! is_array( $db_list ) )
1026 if ( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
1028 $details = $global_db_list[ mt_rand( 0, count( $global_db_list ) -1 ) ];
1029 $this->db_global = $details;
1030 } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
1032 $details = $db_list[ 'write' ][ mt_rand( 0, count( $db_list[ 'write' ] ) -1 ) ];
1033 $this->db_write = $details;
1036 $details = $db_list[ 'read' ][ mt_rand( 0, count( $db_list[ 'read' ] ) -1 ) ];
1037 $this->db_read = $details;
1040 $dbhname = "dbh" . $action;
1041 $this->$dbhname = @mysql_connect( $details[ 'db_host' ], $details[ 'db_user' ], $details[ 'db_password' ] );
1042 if (!$this->$dbhname ) {
1043 $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/"
1044 <h1>Error establishing a database connection</h1>
1045 <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>
1047 <li>Are you sure you have the correct username and password?</li>
1048 <li>Are you sure that you have typed the correct hostname?</li>
1049 <li>Are you sure that the database server is running?</li>
1051 <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>
1052 "/*/WP_I18N_DB_CONN_ERROR*/, $details['db_host'] ), 'db_connect_fail' );
1054 $this->select( $details[ 'db_name' ], $this->$dbhname );
1058 * Perform a MySQL database query, using current database connection.
1060 * More information can be found on the codex page.
1064 * @param string $query Database query
1065 * @return int|false Number of rows affected/selected or false on error
1067 function query( $query ) {
1068 if ( ! $this->ready )
1071 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1072 if ( function_exists( 'apply_filters' ) )
1073 $query = apply_filters( 'query', $query );
1078 // Log how the function was called
1079 $this->func_call = "\$db->query(\"$query\")";
1081 // Keep track of the last query for debug..
1082 $this->last_query = $query;
1084 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1085 $this->timer_start();
1087 // use $this->dbh for read ops, and $this->dbhwrite for write ops
1088 // use $this->dbhglobal for gloal table ops
1090 if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB ) {
1091 if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
1092 if( false == isset( $this->dbhglobal ) ) {
1093 $this->db_connect( $query );
1095 $dbh =& $this->dbhglobal;
1096 $this->last_db_used = "global";
1097 } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
1098 if( false == isset( $this->dbhwrite ) ) {
1099 $this->db_connect( $query );
1101 $dbh =& $this->dbhwrite;
1102 $this->last_db_used = "write";
1105 $this->last_db_used = "read";
1109 $this->last_db_used = "other/read";
1112 $this->result = @mysql_query( $query, $dbh );
1113 $this->num_queries++;
1115 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1116 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1118 // If there is an error then take note of it..
1119 if ( $this->last_error = mysql_error( $dbh ) ) {
1120 $this->print_error();
1124 if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) {
1125 $this->rows_affected = mysql_affected_rows( $dbh );
1126 // Take note of the insert_id
1127 if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) {
1128 $this->insert_id = mysql_insert_id($dbh);
1130 // Return number of rows affected
1131 $return_val = $this->rows_affected;
1134 while ( $i < @mysql_num_fields( $this->result ) ) {
1135 $this->col_info[$i] = @mysql_fetch_field( $this->result );
1139 while ( $row = @mysql_fetch_object( $this->result ) ) {
1140 $this->last_result[$num_rows] = $row;
1144 @mysql_free_result( $this->result );
1146 // Log number of rows the query returned
1147 // and return number of rows selected
1148 $this->num_rows = $num_rows;
1149 $return_val = $num_rows;
1156 * Insert a row into a table.
1159 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1160 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1164 * @see wpdb::prepare()
1165 * @see wpdb::$field_types
1166 * @see wp_set_wpdb_vars()
1168 * @param string $table table name
1169 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1170 * @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.
1171 * 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.
1172 * @return int|false The number of rows inserted, or false on error.
1174 function insert( $table, $data, $format = null ) {
1175 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1179 * Replace a row into a table.
1182 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1183 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1187 * @see wpdb::prepare()
1188 * @see wpdb::$field_types
1189 * @see wp_set_wpdb_vars()
1191 * @param string $table table name
1192 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1193 * @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.
1194 * 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.
1195 * @return int|false The number of rows affected, or false on error.
1197 function replace( $table, $data, $format = null ) {
1198 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1202 * Helper function for insert and replace.
1204 * Runs an insert or replace query based on $type argument.
1208 * @see wpdb::prepare()
1209 * @see wpdb::$field_types
1210 * @see wp_set_wpdb_vars()
1212 * @param string $table table name
1213 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1214 * @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.
1215 * 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.
1216 * @return int|false The number of rows affected, or false on error.
1218 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1219 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1221 $formats = $format = (array) $format;
1222 $fields = array_keys( $data );
1223 $formatted_fields = array();
1224 foreach ( $fields as $field ) {
1225 if ( !empty( $format ) )
1226 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1227 elseif ( isset( $this->field_types[$field] ) )
1228 $form = $this->field_types[$field];
1231 $formatted_fields[] = $form;
1233 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
1234 return $this->query( $this->prepare( $sql, $data ) );
1238 * Update a row in the table
1241 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1242 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1246 * @see wpdb::prepare()
1247 * @see wpdb::$field_types
1248 * @see wp_set_wpdb_vars()
1250 * @param string $table table name
1251 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1252 * @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".
1253 * @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.
1254 * 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.
1255 * @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.
1256 * @return int|false The number of rows updated, or false on error.
1258 function update( $table, $data, $where, $format = null, $where_format = null ) {
1259 if ( ! is_array( $data ) || ! is_array( $where ) )
1262 $formats = $format = (array) $format;
1263 $bits = $wheres = array();
1264 foreach ( (array) array_keys( $data ) as $field ) {
1265 if ( !empty( $format ) )
1266 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1267 elseif ( isset($this->field_types[$field]) )
1268 $form = $this->field_types[$field];
1271 $bits[] = "`$field` = {$form}";
1274 $where_formats = $where_format = (array) $where_format;
1275 foreach ( (array) array_keys( $where ) as $field ) {
1276 if ( !empty( $where_format ) )
1277 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1278 elseif ( isset( $this->field_types[$field] ) )
1279 $form = $this->field_types[$field];
1282 $wheres[] = "`$field` = {$form}";
1285 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1286 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1290 * Retrieve one variable from the database.
1292 * Executes a SQL query and returns the value from the SQL result.
1293 * 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.
1294 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1298 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1299 * @param int $x Optional. Column of value to return. Indexed from 0.
1300 * @param int $y Optional. Row of value to return. Indexed from 0.
1301 * @return string|null Database query result (as string), or null on failure
1303 function get_var( $query = null, $x = 0, $y = 0 ) {
1304 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1306 $this->query( $query );
1308 // Extract var out of cached results based x,y vals
1309 if ( !empty( $this->last_result[$y] ) ) {
1310 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1313 // If there is a value return it else return null
1314 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1318 * Retrieve one row from the database.
1320 * Executes a SQL query and returns the row from the SQL result.
1324 * @param string|null $query SQL query.
1325 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1326 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1327 * @param int $y Optional. Row to return. Indexed from 0.
1328 * @return mixed Database query result in format specifed by $output or null on failure
1330 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1331 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1333 $this->query( $query );
1337 if ( !isset( $this->last_result[$y] ) )
1340 if ( $output == OBJECT ) {
1341 return $this->last_result[$y] ? $this->last_result[$y] : null;
1342 } elseif ( $output == ARRAY_A ) {
1343 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1344 } elseif ( $output == ARRAY_N ) {
1345 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1347 $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*/);
1352 * Retrieve one column from the database.
1354 * Executes a SQL query and returns the column from the SQL result.
1355 * If the SQL result contains more than one column, this function returns the column specified.
1356 * If $query is null, this function returns the specified column from the previous SQL result.
1360 * @param string|null $query Optional. SQL query. Defaults to previous query.
1361 * @param int $x Optional. Column to return. Indexed from 0.
1362 * @return array Database query result. Array indexed from 0 by SQL result row number.
1364 function get_col( $query = null , $x = 0 ) {
1366 $this->query( $query );
1368 $new_array = array();
1369 // Extract the column values
1370 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1371 $new_array[$i] = $this->get_var( null, $x, $i );
1377 * Retrieve an entire SQL result set from the database (i.e., many rows)
1379 * Executes a SQL query and returns the entire SQL result.
1383 * @param string $query SQL query.
1384 * @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.
1385 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1386 * 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.
1387 * @return mixed Database query results
1389 function get_results( $query = null, $output = OBJECT ) {
1390 $this->func_call = "\$db->get_results(\"$query\", $output)";
1393 $this->query( $query );
1397 $new_array = array();
1398 if ( $output == OBJECT ) {
1399 // Return an integer-keyed array of row objects
1400 return $this->last_result;
1401 } elseif ( $output == OBJECT_K ) {
1402 // Return an array of row objects with keys from column 1
1403 // (Duplicates are discarded)
1404 foreach ( $this->last_result as $row ) {
1405 $key = array_shift( $var_by_ref = get_object_vars( $row ) );
1406 if ( ! isset( $new_array[ $key ] ) )
1407 $new_array[ $key ] = $row;
1410 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1411 // Return an integer-keyed array of...
1412 if ( $this->last_result ) {
1413 foreach( (array) $this->last_result as $row ) {
1414 if ( $output == ARRAY_N ) {
1415 // ...integer-keyed row arrays
1416 $new_array[] = array_values( get_object_vars( $row ) );
1418 // ...column name-keyed row arrays
1419 $new_array[] = get_object_vars( $row );
1429 * Retrieve column metadata from the last query.
1433 * @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
1434 * @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
1435 * @return mixed Column Results
1437 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1438 if ( $this->col_info ) {
1439 if ( $col_offset == -1 ) {
1441 $new_array = array();
1442 foreach( (array) $this->col_info as $col ) {
1443 $new_array[$i] = $col->{$info_type};
1448 return $this->col_info[$col_offset]->{$info_type};
1454 * Starts the timer, for debugging purposes.
1460 function timer_start() {
1461 $mtime = explode( ' ', microtime() );
1462 $this->time_start = $mtime[1] + $mtime[0];
1467 * Stops the debugging timer.
1471 * @return int Total time spent on the query, in milliseconds
1473 function timer_stop() {
1474 $mtime = explode( ' ', microtime() );
1475 $time_end = $mtime[1] + $mtime[0];
1476 $time_total = $time_end - $this->time_start;
1481 * Wraps errors in a nice header and footer and dies.
1483 * Will not die if wpdb::$show_errors is true
1487 * @param string $message The Error message
1488 * @param string $error_code Optional. A Computer readable string to identify the error.
1489 * @return false|void
1491 function bail( $message, $error_code = '500' ) {
1492 if ( !$this->show_errors ) {
1493 if ( class_exists( 'WP_Error' ) )
1494 $this->error = new WP_Error($error_code, $message);
1496 $this->error = $message;
1503 * Whether MySQL database is at least the required minimum version.
1507 * @uses $required_mysql_version
1511 function check_database_version() {
1512 global $wp_version, $required_mysql_version;
1513 // Make sure the server has the required MySQL version
1514 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1515 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1519 * Whether the database supports collation.
1521 * Called when WordPress is generating the table scheme.
1525 * @return bool True if collation is supported, false if version does not
1527 function supports_collation() {
1528 return $this->has_cap( 'collation' );
1532 * Determine if a database supports a particular feature
1535 * @see wpdb::db_version()
1537 * @param string $db_cap the feature
1540 function has_cap( $db_cap ) {
1541 $version = $this->db_version();
1543 switch ( strtolower( $db_cap ) ) {
1544 case 'collation' : // @since 2.5.0
1545 case 'group_concat' : // @since 2.7
1546 case 'subqueries' : // @since 2.7
1547 return version_compare( $version, '4.1', '>=' );
1554 * Retrieve the name of the function that called wpdb.
1556 * Searches up the list of functions until it reaches
1557 * the one that would most logically had called this method.
1561 * @return string The name of the calling function
1563 function get_caller() {
1564 $trace = array_reverse( debug_backtrace() );
1567 foreach ( $trace as $call ) {
1568 if ( isset( $call['class'] ) && __CLASS__ == $call['class'] )
1569 continue; // Filter out wpdb calls.
1570 $caller[] = isset( $call['class'] ) ? "{$call['class']}->{$call['function']}" : $call['function'];
1573 return join( ', ', $caller );
1577 * The database version number.
1579 * @return false|string false on failure, version number on success
1581 function db_version() {
1582 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );
1586 if ( ! isset( $wpdb ) ) {
1588 * WordPress Database Object, if it isn't set already in wp-content/db.php
1589 * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
1592 $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );