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.
74 * @see get_last_error()
82 * Amount of queries made
91 * Count of rows returned by previous query
100 * Count of affected rows by previous query
106 var $rows_affected = 0;
109 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
118 * Saved result of the last query made
127 * Results of the last query made
136 * Saved info on the table column
145 * Saved queries that were executed
154 * WordPress table prefix
156 * You can set this to have multiple WordPress installations
157 * in a single database. The second reason is for possible
158 * security precautions.
167 * Whether the database queries are ready to start executing.
176 * {@internal Missing Description}}
185 * {@internal Missing Description}}
194 * List of WordPress per-blog tables
198 * @see wpdb::tables()
201 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
202 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
205 * List of deprecated WordPress tables
207 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
211 * @see wpdb::tables()
214 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
217 * List of WordPress global tables
221 * @see wpdb::tables()
224 var $global_tables = array( 'users', 'usermeta' );
227 * List of Multisite global tables
231 * @see wpdb::tables()
234 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
235 'sitecategories', 'registration_log', 'blog_versions' );
238 * WordPress Comments table
247 * WordPress Comment Metadata table
256 * WordPress Links table
265 * WordPress Options table
274 * WordPress Post Metadata table
283 * WordPress Posts table
292 * WordPress Terms table
301 * WordPress Term Relationships table
307 var $term_relationships;
310 * WordPress Term Taxonomy table
319 * Global and Multisite tables
323 * WordPress User Metadata table
332 * WordPress Users table
341 * Multisite Blogs table
350 * Multisite Blog Versions table
359 * Multisite Registration Log table
365 var $registration_log;
368 * Multisite Signups table
377 * Multisite Sites table
386 * Multisite Sitewide Terms table
395 * Multisite Site Metadata table
404 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
406 * Keys are column names, values are format types: 'ID' => '%d'
409 * @see wpdb:prepare()
412 * @see wp_set_wpdb_vars()
416 var $field_types = array();
419 * Database table columns charset
428 * Database table columns collate
437 * Whether to use mysql_real_escape_string
443 var $real_escape = false;
455 * A textual description of the last query/get_row/get_var call
464 * Connects to the database server and selects a database
466 * PHP5 style constructor for compatibility with PHP5. Does
467 * the actual setting up of the class properties and connection
470 * @link http://core.trac.wordpress.org/ticket/3354
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 __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
479 register_shutdown_function( array( &$this, '__destruct' ) );
482 $this->show_errors();
484 $this->init_charset();
486 $this->dbuser = $dbuser;
487 $this->dbpassword = $dbpassword;
488 $this->dbname = $dbname;
489 $this->dbhost = $dbhost;
495 * PHP5 style destructor and will run when database object is destroyed.
497 * @see wpdb::__construct()
501 function __destruct() {
506 * Set $this->charset and $this->collate
510 function init_charset() {
511 if ( function_exists('is_multisite') && is_multisite() ) {
512 $this->charset = 'utf8';
513 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
514 $this->collate = DB_COLLATE;
516 $this->collate = 'utf8_general_ci';
517 } elseif ( defined( 'DB_COLLATE' ) ) {
518 $this->collate = DB_COLLATE;
521 if ( defined( 'DB_CHARSET' ) )
522 $this->charset = DB_CHARSET;
526 * Sets the connection's character set.
530 * @param resource $dbh The resource given by mysql_connect
531 * @param string $charset The character set (optional)
532 * @param string $collate The collation (optional)
534 function set_charset($dbh, $charset = null, $collate = null) {
535 if ( !isset($charset) )
536 $charset = $this->charset;
537 if ( !isset($collate) )
538 $collate = $this->collate;
539 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
540 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
541 mysql_set_charset( $charset, $dbh );
542 $this->real_escape = true;
544 $query = $this->prepare( 'SET NAMES %s', $charset );
545 if ( ! empty( $collate ) )
546 $query .= $this->prepare( ' COLLATE %s', $collate );
547 mysql_query( $query, $dbh );
553 * Sets the table prefix for the WordPress tables.
557 * @param string $prefix Alphanumeric name for the new prefix.
558 * @return string|WP_Error Old prefix or WP_Error on error
560 function set_prefix( $prefix, $set_table_names = true ) {
562 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
563 return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
565 $old_prefix = is_multisite() ? '' : $prefix;
567 if ( isset( $this->base_prefix ) )
568 $old_prefix = $this->base_prefix;
570 $this->base_prefix = $prefix;
572 if ( $set_table_names ) {
573 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
574 $this->$table = $prefixed_table;
576 if ( is_multisite() && empty( $this->blogid ) )
579 $this->prefix = $this->get_blog_prefix();
581 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
582 $this->$table = $prefixed_table;
584 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
585 $this->$table = $prefixed_table;
595 * @param int $blog_id
596 * @param int $site_id Optional.
597 * @return string previous blog id
599 function set_blog_id( $blog_id, $site_id = 0 ) {
600 if ( ! empty( $site_id ) )
601 $this->siteid = $site_id;
603 $old_blog_id = $this->blogid;
604 $this->blogid = $blog_id;
606 $this->prefix = $this->get_blog_prefix();
608 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
609 $this->$table = $prefixed_table;
611 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
612 $this->$table = $prefixed_table;
620 * @uses is_multisite()
622 * @param int $blog_id Optional.
623 * @return string Blog prefix.
625 function get_blog_prefix( $blog_id = null ) {
626 if ( is_multisite() ) {
627 if ( null === $blog_id )
628 $blog_id = $this->blogid;
629 $blog_id = (int) $blog_id;
630 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
631 return $this->base_prefix;
633 return $this->base_prefix . $blog_id . '_';
635 return $this->base_prefix;
640 * Returns an array of WordPress tables.
642 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
643 * override the WordPress users and usersmeta tables that would otherwise
644 * be determined by the prefix.
646 * The scope argument can take one of the following:
648 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
649 * 'blog' - returns the blog-level tables for the queried blog.
650 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
651 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
652 * 'old' - returns tables which are deprecated.
655 * @uses wpdb::$tables
656 * @uses wpdb::$old_tables
657 * @uses wpdb::$global_tables
658 * @uses wpdb::$ms_global_tables
659 * @uses is_multisite()
661 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
662 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
663 * prefix is requested, then the custom users and usermeta tables will be mapped.
664 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
665 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
667 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
670 $tables = array_merge( $this->global_tables, $this->tables );
671 if ( is_multisite() )
672 $tables = array_merge( $tables, $this->ms_global_tables );
675 $tables = $this->tables;
678 $tables = $this->global_tables;
679 if ( is_multisite() )
680 $tables = array_merge( $tables, $this->ms_global_tables );
683 $tables = $this->ms_global_tables;
686 $tables = $this->old_tables;
695 $blog_id = $this->blogid;
696 $blog_prefix = $this->get_blog_prefix( $blog_id );
697 $base_prefix = $this->base_prefix;
698 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
699 foreach ( $tables as $k => $table ) {
700 if ( in_array( $table, $global_tables ) )
701 $tables[ $table ] = $base_prefix . $table;
703 $tables[ $table ] = $blog_prefix . $table;
704 unset( $tables[ $k ] );
707 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
708 $tables['users'] = CUSTOM_USER_TABLE;
710 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
711 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
718 * Selects a database using the current database connection.
720 * The database name will be changed based on the current database
721 * connection. On failure, the execution will bail and display an DB error.
725 * @param string $db MySQL database name
726 * @param resource $dbh Optional link identifier.
727 * @return null Always null.
729 function select( $db, $dbh = null) {
733 if ( !@mysql_select_db( $db, $dbh ) ) {
734 $this->ready = false;
735 $this->bail( sprintf( /*WP_I18N_DB_SELECT_DB*/'<h1>Can’t select database</h1>
736 <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>
738 <li>Are you sure it exists?</li>
739 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
740 <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>
742 <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' );
748 * Weak escape, using addslashes()
754 * @param string $string
757 function _weak_escape( $string ) {
758 return addslashes( $string );
762 * Real escape, using mysql_real_escape_string() or addslashes()
764 * @see mysql_real_escape_string()
769 * @param string $string to escape
770 * @return string escaped
772 function _real_escape( $string ) {
773 if ( $this->dbh && $this->real_escape )
774 return mysql_real_escape_string( $string, $this->dbh );
776 return addslashes( $string );
780 * Escape data. Works on arrays.
782 * @uses wpdb::_escape()
783 * @uses wpdb::_real_escape()
787 * @param string|array $data
788 * @return string|array escaped
790 function _escape( $data ) {
791 if ( is_array( $data ) ) {
792 foreach ( (array) $data as $k => $v ) {
794 $data[$k] = $this->_escape( $v );
796 $data[$k] = $this->_real_escape( $v );
799 $data = $this->_real_escape( $data );
806 * Escapes content for insertion into the database using addslashes(), for security.
811 * @param string|array $data to escape
812 * @return string|array escaped as query safe string
814 function escape( $data ) {
815 if ( is_array( $data ) ) {
816 foreach ( (array) $data as $k => $v ) {
817 if ( is_array( $v ) )
818 $data[$k] = $this->escape( $v );
820 $data[$k] = $this->_weak_escape( $v );
823 $data = $this->_weak_escape( $data );
830 * Escapes content by reference for insertion into the database, for security
832 * @uses wpdb::_real_escape()
834 * @param string $string to escape
837 function escape_by_ref( &$string ) {
838 $string = $this->_real_escape( $string );
842 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
844 * The following directives can be used in the query format string:
845 * %d (decimal number)
847 * %% (literal percentage sign - no argument needed)
849 * Both %d and %s are to be left unquoted in the query string and they need an argument passed for them.
850 * Literals (%) as parts of the query must be properly written as %%.
852 * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
853 * Does not support sign, padding, alignment, width or precision specifiers.
854 * Does not support argument numbering/swapping.
856 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
858 * Both %d and %s should be left unquoted in the query string.
861 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
862 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
865 * @link http://php.net/sprintf Description of syntax.
868 * @param string $query Query statement with sprintf()-like placeholders
869 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
870 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
871 * being called like {@link http://php.net/sprintf sprintf()}.
872 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
873 * {@link http://php.net/sprintf sprintf()}.
874 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
875 * if there was something to prepare
877 function prepare( $query = null ) { // ( $query, *$args )
878 if ( is_null( $query ) )
881 $args = func_get_args();
882 array_shift( $args );
883 // If args were passed as an array (as in vsprintf), move them up
884 if ( isset( $args[0] ) && is_array($args[0]) )
886 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
887 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
888 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
889 array_walk( $args, array( &$this, 'escape_by_ref' ) );
890 return @vsprintf( $query, $args );
894 * Print SQL/DB error.
897 * @global array $EZSQL_ERROR Stores error information of query and error string
899 * @param string $str The error to display
900 * @return bool False if the showing of errors is disabled.
902 function print_error( $str = '' ) {
906 $str = mysql_error( $this->dbh );
907 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
909 if ( $this->suppress_errors )
912 if ( $caller = $this->get_caller() )
913 $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 );
915 $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 );
917 if ( function_exists( 'error_log' )
918 && ( $log_file = @ini_get( 'error_log' ) )
919 && ( 'syslog' == $log_file || @is_writable( $log_file ) )
921 @error_log( $error_str );
923 // Are we showing errors?
924 if ( ! $this->show_errors )
927 // If there is an error then take note of it
928 if ( is_multisite() ) {
929 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
930 if ( defined( 'ERRORLOGFILE' ) )
931 error_log( $msg, 3, ERRORLOGFILE );
932 if ( defined( 'DIEONDBERROR' ) )
935 $str = htmlspecialchars( $str, ENT_QUOTES );
936 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
938 print "<div id='error'>
939 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
940 <code>$query</code></p>
946 * Enables showing of database errors.
948 * This function should be used only to enable showing of errors.
949 * wpdb::hide_errors() should be used instead for hiding of errors. However,
950 * this function can be used to enable and disable showing of database
954 * @see wpdb::hide_errors()
956 * @param bool $show Whether to show or hide errors
957 * @return bool Old value for showing errors.
959 function show_errors( $show = true ) {
960 $errors = $this->show_errors;
961 $this->show_errors = $show;
966 * Disables showing of database errors.
968 * By default database errors are not shown.
971 * @see wpdb::show_errors()
973 * @return bool Whether showing of errors was active
975 function hide_errors() {
976 $show = $this->show_errors;
977 $this->show_errors = false;
982 * Whether to suppress database errors.
984 * By default database errors are suppressed, with a simple
985 * call to this function they can be enabled.
988 * @see wpdb::hide_errors()
989 * @param bool $suppress Optional. New value. Defaults to true.
990 * @return bool Old value
992 function suppress_errors( $suppress = true ) {
993 $errors = $this->suppress_errors;
994 $this->suppress_errors = (bool) $suppress;
999 * Kill cached query results.
1005 $this->last_result = array();
1006 $this->col_info = null;
1007 $this->last_query = null;
1011 * Connect to and select database
1015 function db_connect() {
1017 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1019 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1022 if ( !$this->dbh ) {
1023 $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/"
1024 <h1>Error establishing a database connection</h1>
1025 <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>
1027 <li>Are you sure you have the correct username and password?</li>
1028 <li>Are you sure that you have typed the correct hostname?</li>
1029 <li>Are you sure that the database server is running?</li>
1031 <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>
1032 "/*/WP_I18N_DB_CONN_ERROR*/, $this->dbhost ), 'db_connect_fail' );
1037 $this->set_charset( $this->dbh );
1039 $this->ready = true;
1041 $this->select( $this->dbname, $this->dbh );
1045 * Perform a MySQL database query, using current database connection.
1047 * More information can be found on the codex page.
1051 * @param string $query Database query
1052 * @return int|false Number of rows affected/selected or false on error
1054 function query( $query ) {
1055 if ( ! $this->ready )
1058 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1059 if ( function_exists( 'apply_filters' ) )
1060 $query = apply_filters( 'query', $query );
1065 // Log how the function was called
1066 $this->func_call = "\$db->query(\"$query\")";
1068 // Keep track of the last query for debug..
1069 $this->last_query = $query;
1071 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1072 $this->timer_start();
1074 $this->result = @mysql_query( $query, $this->dbh );
1075 $this->num_queries++;
1077 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1078 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1080 // If there is an error then take note of it..
1081 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1082 $this->print_error();
1086 if ( preg_match( '/^\s*(create|alter|truncate|drop) /i', $query ) ) {
1087 $return_val = $this->result;
1088 } elseif ( preg_match( '/^\s*(insert|delete|update|replace) /i', $query ) ) {
1089 $this->rows_affected = mysql_affected_rows( $this->dbh );
1090 // Take note of the insert_id
1091 if ( preg_match( '/^\s*(insert|replace) /i', $query ) ) {
1092 $this->insert_id = mysql_insert_id($this->dbh);
1094 // Return number of rows affected
1095 $return_val = $this->rows_affected;
1098 while ( $i < @mysql_num_fields( $this->result ) ) {
1099 $this->col_info[$i] = @mysql_fetch_field( $this->result );
1103 while ( $row = @mysql_fetch_object( $this->result ) ) {
1104 $this->last_result[$num_rows] = $row;
1108 @mysql_free_result( $this->result );
1110 // Log number of rows the query returned
1111 // and return number of rows selected
1112 $this->num_rows = $num_rows;
1113 $return_val = $num_rows;
1120 * Insert a row into a table.
1123 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1124 * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1128 * @see wpdb::prepare()
1129 * @see wpdb::$field_types
1130 * @see wp_set_wpdb_vars()
1132 * @param string $table table name
1133 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1134 * @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.
1135 * 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.
1136 * @return int|false The number of rows inserted, or false on error.
1138 function insert( $table, $data, $format = null ) {
1139 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1143 * Replace a row into a table.
1146 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1147 * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1151 * @see wpdb::prepare()
1152 * @see wpdb::$field_types
1153 * @see wp_set_wpdb_vars()
1155 * @param string $table table name
1156 * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1157 * @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.
1158 * 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.
1159 * @return int|false The number of rows affected, or false on error.
1161 function replace( $table, $data, $format = null ) {
1162 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1166 * Helper function for insert and replace.
1168 * Runs an insert or replace query based on $type argument.
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', '%s' (decimal number, 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 _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1183 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1185 $formats = $format = (array) $format;
1186 $fields = array_keys( $data );
1187 $formatted_fields = array();
1188 foreach ( $fields as $field ) {
1189 if ( !empty( $format ) )
1190 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1191 elseif ( isset( $this->field_types[$field] ) )
1192 $form = $this->field_types[$field];
1195 $formatted_fields[] = $form;
1197 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
1198 return $this->query( $this->prepare( $sql, $data ) );
1202 * Update a row in the table
1205 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1206 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1210 * @see wpdb::prepare()
1211 * @see wpdb::$field_types
1212 * @see wp_set_wpdb_vars()
1214 * @param string $table table name
1215 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1216 * @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".
1217 * @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.
1218 * 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.
1219 * @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.
1220 * @return int|false The number of rows updated, or false on error.
1222 function update( $table, $data, $where, $format = null, $where_format = null ) {
1223 if ( ! is_array( $data ) || ! is_array( $where ) )
1226 $formats = $format = (array) $format;
1227 $bits = $wheres = array();
1228 foreach ( (array) array_keys( $data ) as $field ) {
1229 if ( !empty( $format ) )
1230 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1231 elseif ( isset($this->field_types[$field]) )
1232 $form = $this->field_types[$field];
1235 $bits[] = "`$field` = {$form}";
1238 $where_formats = $where_format = (array) $where_format;
1239 foreach ( (array) array_keys( $where ) as $field ) {
1240 if ( !empty( $where_format ) )
1241 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1242 elseif ( isset( $this->field_types[$field] ) )
1243 $form = $this->field_types[$field];
1246 $wheres[] = "`$field` = {$form}";
1249 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1250 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1254 * Retrieve one variable from the database.
1256 * Executes a SQL query and returns the value from the SQL result.
1257 * 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.
1258 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1262 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1263 * @param int $x Optional. Column of value to return. Indexed from 0.
1264 * @param int $y Optional. Row of value to return. Indexed from 0.
1265 * @return string|null Database query result (as string), or null on failure
1267 function get_var( $query = null, $x = 0, $y = 0 ) {
1268 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1270 $this->query( $query );
1272 // Extract var out of cached results based x,y vals
1273 if ( !empty( $this->last_result[$y] ) ) {
1274 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1277 // If there is a value return it else return null
1278 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1282 * Retrieve one row from the database.
1284 * Executes a SQL query and returns the row from the SQL result.
1288 * @param string|null $query SQL query.
1289 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1290 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1291 * @param int $y Optional. Row to return. Indexed from 0.
1292 * @return mixed Database query result in format specifed by $output or null on failure
1294 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1295 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1297 $this->query( $query );
1301 if ( !isset( $this->last_result[$y] ) )
1304 if ( $output == OBJECT ) {
1305 return $this->last_result[$y] ? $this->last_result[$y] : null;
1306 } elseif ( $output == ARRAY_A ) {
1307 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1308 } elseif ( $output == ARRAY_N ) {
1309 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1311 $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*/);
1316 * Retrieve one column from the database.
1318 * Executes a SQL query and returns the column from the SQL result.
1319 * If the SQL result contains more than one column, this function returns the column specified.
1320 * If $query is null, this function returns the specified column from the previous SQL result.
1324 * @param string|null $query Optional. SQL query. Defaults to previous query.
1325 * @param int $x Optional. Column to return. Indexed from 0.
1326 * @return array Database query result. Array indexed from 0 by SQL result row number.
1328 function get_col( $query = null , $x = 0 ) {
1330 $this->query( $query );
1332 $new_array = array();
1333 // Extract the column values
1334 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1335 $new_array[$i] = $this->get_var( null, $x, $i );
1341 * Retrieve an entire SQL result set from the database (i.e., many rows)
1343 * Executes a SQL query and returns the entire SQL result.
1347 * @param string $query SQL query.
1348 * @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.
1349 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1350 * 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.
1351 * @return mixed Database query results
1353 function get_results( $query = null, $output = OBJECT ) {
1354 $this->func_call = "\$db->get_results(\"$query\", $output)";
1357 $this->query( $query );
1361 $new_array = array();
1362 if ( $output == OBJECT ) {
1363 // Return an integer-keyed array of row objects
1364 return $this->last_result;
1365 } elseif ( $output == OBJECT_K ) {
1366 // Return an array of row objects with keys from column 1
1367 // (Duplicates are discarded)
1368 foreach ( $this->last_result as $row ) {
1369 $key = array_shift( get_object_vars( $row ) );
1370 if ( ! isset( $new_array[ $key ] ) )
1371 $new_array[ $key ] = $row;
1374 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1375 // Return an integer-keyed array of...
1376 if ( $this->last_result ) {
1377 foreach( (array) $this->last_result as $row ) {
1378 if ( $output == ARRAY_N ) {
1379 // ...integer-keyed row arrays
1380 $new_array[] = array_values( get_object_vars( $row ) );
1382 // ...column name-keyed row arrays
1383 $new_array[] = get_object_vars( $row );
1393 * Retrieve column metadata from the last query.
1397 * @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
1398 * @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
1399 * @return mixed Column Results
1401 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1402 if ( $this->col_info ) {
1403 if ( $col_offset == -1 ) {
1405 $new_array = array();
1406 foreach( (array) $this->col_info as $col ) {
1407 $new_array[$i] = $col->{$info_type};
1412 return $this->col_info[$col_offset]->{$info_type};
1418 * Starts the timer, for debugging purposes.
1424 function timer_start() {
1425 $mtime = explode( ' ', microtime() );
1426 $this->time_start = $mtime[1] + $mtime[0];
1431 * Stops the debugging timer.
1435 * @return int Total time spent on the query, in milliseconds
1437 function timer_stop() {
1438 $mtime = explode( ' ', microtime() );
1439 $time_end = $mtime[1] + $mtime[0];
1440 $time_total = $time_end - $this->time_start;
1445 * Wraps errors in a nice header and footer and dies.
1447 * Will not die if wpdb::$show_errors is true
1451 * @param string $message The Error message
1452 * @param string $error_code Optional. A Computer readable string to identify the error.
1453 * @return false|void
1455 function bail( $message, $error_code = '500' ) {
1456 if ( !$this->show_errors ) {
1457 if ( class_exists( 'WP_Error' ) )
1458 $this->error = new WP_Error($error_code, $message);
1460 $this->error = $message;
1467 * Whether MySQL database is at least the required minimum version.
1471 * @uses $required_mysql_version
1475 function check_database_version() {
1476 global $wp_version, $required_mysql_version;
1477 // Make sure the server has the required MySQL version
1478 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1479 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1483 * Whether the database supports collation.
1485 * Called when WordPress is generating the table scheme.
1489 * @return bool True if collation is supported, false if version does not
1491 function supports_collation() {
1492 return $this->has_cap( 'collation' );
1496 * Determine if a database supports a particular feature
1499 * @see wpdb::db_version()
1501 * @param string $db_cap the feature
1504 function has_cap( $db_cap ) {
1505 $version = $this->db_version();
1507 switch ( strtolower( $db_cap ) ) {
1508 case 'collation' : // @since 2.5.0
1509 case 'group_concat' : // @since 2.7
1510 case 'subqueries' : // @since 2.7
1511 return version_compare( $version, '4.1', '>=' );
1512 case 'set_charset' :
1513 return version_compare($version, '5.0.7', '>=');
1520 * Retrieve the name of the function that called wpdb.
1522 * Searches up the list of functions until it reaches
1523 * the one that would most logically had called this method.
1527 * @return string The name of the calling function
1529 function get_caller() {
1530 $trace = array_reverse( debug_backtrace() );
1533 foreach ( $trace as $call ) {
1534 if ( isset( $call['class'] ) && __CLASS__ == $call['class'] )
1535 continue; // Filter out wpdb calls.
1536 $caller[] = isset( $call['class'] ) ? "{$call['class']}->{$call['function']}" : $call['function'];
1539 return join( ', ', $caller );
1543 * The database version number.
1547 * @return false|string false on failure, version number on success
1549 function db_version() {
1550 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );