5 * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
15 define( 'EZSQL_VERSION', 'WP1.25' );
20 define( 'OBJECT', 'OBJECT', true );
25 define( 'OBJECT_K', 'OBJECT_K' );
30 define( 'ARRAY_A', 'ARRAY_A' );
35 define( 'ARRAY_N', 'ARRAY_N' );
38 * WordPress Database Access Abstraction Object
40 * It is possible to replace this class with your own
41 * by setting the $wpdb global variable in wp-content/db.php
42 * file to your class. The wpdb class will still be included,
43 * so you can extend it or simply use your own.
45 * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
48 * @subpackage Database
54 * Whether to show SQL/DB errors
60 var $show_errors = false;
63 * Whether to suppress errors during the DB bootstrapping.
69 var $suppress_errors = false;
72 * The last error during query.
80 * Amount of queries made
89 * Count of rows returned by previous query
98 * Count of affected rows by previous query
104 var $rows_affected = 0;
107 * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
116 * Saved result of the last query made
125 * Results of the last query made
134 * Saved info on the table column
143 * Saved queries that were executed
152 * WordPress table prefix
154 * You can set this to have multiple WordPress installations
155 * in a single database. The second reason is for possible
156 * security precautions.
165 * Whether the database queries are ready to start executing.
174 * {@internal Missing Description}}
183 * {@internal Missing Description}}
192 * List of WordPress per-blog tables
196 * @see wpdb::tables()
199 var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
200 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
203 * List of deprecated WordPress tables
205 * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
209 * @see wpdb::tables()
212 var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
215 * List of WordPress global tables
219 * @see wpdb::tables()
222 var $global_tables = array( 'users', 'usermeta' );
225 * List of Multisite global tables
229 * @see wpdb::tables()
232 var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
233 'sitecategories', 'registration_log', 'blog_versions' );
236 * WordPress Comments table
245 * WordPress Comment Metadata table
254 * WordPress Links table
263 * WordPress Options table
272 * WordPress Post Metadata table
281 * WordPress Posts table
290 * WordPress Terms table
299 * WordPress Term Relationships table
305 var $term_relationships;
308 * WordPress Term Taxonomy table
317 * Global and Multisite tables
321 * WordPress User Metadata table
330 * WordPress Users table
339 * Multisite Blogs table
348 * Multisite Blog Versions table
357 * Multisite Registration Log table
363 var $registration_log;
366 * Multisite Signups table
375 * Multisite Sites table
384 * Multisite Sitewide Terms table
393 * Multisite Site Metadata table
402 * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
404 * Keys are column names, values are format types: 'ID' => '%d'
407 * @see wpdb:prepare()
410 * @see wp_set_wpdb_vars()
414 var $field_types = array();
417 * Database table columns charset
426 * Database table columns collate
435 * Whether to use mysql_real_escape_string
441 var $real_escape = false;
453 * A textual description of the last query/get_row/get_var call
462 * Whether MySQL is used as the database engine.
464 * Set in WPDB::db_connect() to true, by default. This is used when checking
465 * against the required MySQL version for WordPress. Normally, a replacement
466 * database drop-in (db.php) will skip these checks, but setting this to true
467 * will force the checks to occur.
473 public $is_mysql = null;
476 * Connects to the database server and selects a database
478 * PHP5 style constructor for compatibility with PHP5. Does
479 * the actual setting up of the class properties and connection
482 * @link http://core.trac.wordpress.org/ticket/3354
485 * @param string $dbuser MySQL database user
486 * @param string $dbpassword MySQL database password
487 * @param string $dbname MySQL database name
488 * @param string $dbhost MySQL database host
490 function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
491 register_shutdown_function( array( &$this, '__destruct' ) );
494 $this->show_errors();
496 $this->init_charset();
498 $this->dbuser = $dbuser;
499 $this->dbpassword = $dbpassword;
500 $this->dbname = $dbname;
501 $this->dbhost = $dbhost;
507 * PHP5 style destructor and will run when database object is destroyed.
509 * @see wpdb::__construct()
513 function __destruct() {
518 * Set $this->charset and $this->collate
522 function init_charset() {
523 if ( function_exists('is_multisite') && is_multisite() ) {
524 $this->charset = 'utf8';
525 if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
526 $this->collate = DB_COLLATE;
528 $this->collate = 'utf8_general_ci';
529 } elseif ( defined( 'DB_COLLATE' ) ) {
530 $this->collate = DB_COLLATE;
533 if ( defined( 'DB_CHARSET' ) )
534 $this->charset = DB_CHARSET;
538 * Sets the connection's character set.
542 * @param resource $dbh The resource given by mysql_connect
543 * @param string $charset The character set (optional)
544 * @param string $collate The collation (optional)
546 function set_charset($dbh, $charset = null, $collate = null) {
547 if ( !isset($charset) )
548 $charset = $this->charset;
549 if ( !isset($collate) )
550 $collate = $this->collate;
551 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
552 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
553 mysql_set_charset( $charset, $dbh );
554 $this->real_escape = true;
556 $query = $this->prepare( 'SET NAMES %s', $charset );
557 if ( ! empty( $collate ) )
558 $query .= $this->prepare( ' COLLATE %s', $collate );
559 mysql_query( $query, $dbh );
565 * Sets the table prefix for the WordPress tables.
569 * @param string $prefix Alphanumeric name for the new prefix.
570 * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
571 * @return string|WP_Error Old prefix or WP_Error on error
573 function set_prefix( $prefix, $set_table_names = true ) {
575 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
576 return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
578 $old_prefix = is_multisite() ? '' : $prefix;
580 if ( isset( $this->base_prefix ) )
581 $old_prefix = $this->base_prefix;
583 $this->base_prefix = $prefix;
585 if ( $set_table_names ) {
586 foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
587 $this->$table = $prefixed_table;
589 if ( is_multisite() && empty( $this->blogid ) )
592 $this->prefix = $this->get_blog_prefix();
594 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
595 $this->$table = $prefixed_table;
597 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
598 $this->$table = $prefixed_table;
608 * @param int $blog_id
609 * @param int $site_id Optional.
610 * @return string previous blog id
612 function set_blog_id( $blog_id, $site_id = 0 ) {
613 if ( ! empty( $site_id ) )
614 $this->siteid = $site_id;
616 $old_blog_id = $this->blogid;
617 $this->blogid = $blog_id;
619 $this->prefix = $this->get_blog_prefix();
621 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
622 $this->$table = $prefixed_table;
624 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
625 $this->$table = $prefixed_table;
633 * @uses is_multisite()
635 * @param int $blog_id Optional.
636 * @return string Blog prefix.
638 function get_blog_prefix( $blog_id = null ) {
639 if ( is_multisite() ) {
640 if ( null === $blog_id )
641 $blog_id = $this->blogid;
642 $blog_id = (int) $blog_id;
643 if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
644 return $this->base_prefix;
646 return $this->base_prefix . $blog_id . '_';
648 return $this->base_prefix;
653 * Returns an array of WordPress tables.
655 * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
656 * override the WordPress users and usermeta tables that would otherwise
657 * be determined by the prefix.
659 * The scope argument can take one of the following:
661 * 'all' - returns 'all' and 'global' tables. No old tables are returned.
662 * 'blog' - returns the blog-level tables for the queried blog.
663 * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
664 * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
665 * 'old' - returns tables which are deprecated.
668 * @uses wpdb::$tables
669 * @uses wpdb::$old_tables
670 * @uses wpdb::$global_tables
671 * @uses wpdb::$ms_global_tables
672 * @uses is_multisite()
674 * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
675 * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
676 * prefix is requested, then the custom users and usermeta tables will be mapped.
677 * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
678 * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
680 function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
683 $tables = array_merge( $this->global_tables, $this->tables );
684 if ( is_multisite() )
685 $tables = array_merge( $tables, $this->ms_global_tables );
688 $tables = $this->tables;
691 $tables = $this->global_tables;
692 if ( is_multisite() )
693 $tables = array_merge( $tables, $this->ms_global_tables );
696 $tables = $this->ms_global_tables;
699 $tables = $this->old_tables;
708 $blog_id = $this->blogid;
709 $blog_prefix = $this->get_blog_prefix( $blog_id );
710 $base_prefix = $this->base_prefix;
711 $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
712 foreach ( $tables as $k => $table ) {
713 if ( in_array( $table, $global_tables ) )
714 $tables[ $table ] = $base_prefix . $table;
716 $tables[ $table ] = $blog_prefix . $table;
717 unset( $tables[ $k ] );
720 if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
721 $tables['users'] = CUSTOM_USER_TABLE;
723 if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
724 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
731 * Selects a database using the current database connection.
733 * The database name will be changed based on the current database
734 * connection. On failure, the execution will bail and display an DB error.
738 * @param string $db MySQL database name
739 * @param resource $dbh Optional link identifier.
740 * @return null Always null.
742 function select( $db, $dbh = null ) {
746 if ( !@mysql_select_db( $db, $dbh ) ) {
747 $this->ready = false;
748 $this->bail( sprintf( /*WP_I18N_DB_SELECT_DB*/'<h1>Can’t select database</h1>
749 <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>
751 <li>Are you sure it exists?</li>
752 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
753 <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>
755 <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*/, htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
761 * Weak escape, using addslashes()
767 * @param string $string
770 function _weak_escape( $string ) {
771 return addslashes( $string );
775 * Real escape, using mysql_real_escape_string() or addslashes()
777 * @see mysql_real_escape_string()
782 * @param string $string to escape
783 * @return string escaped
785 function _real_escape( $string ) {
786 if ( $this->dbh && $this->real_escape )
787 return mysql_real_escape_string( $string, $this->dbh );
789 return addslashes( $string );
793 * Escape data. Works on arrays.
795 * @uses wpdb::_escape()
796 * @uses wpdb::_real_escape()
800 * @param string|array $data
801 * @return string|array escaped
803 function _escape( $data ) {
804 if ( is_array( $data ) ) {
805 foreach ( (array) $data as $k => $v ) {
807 $data[$k] = $this->_escape( $v );
809 $data[$k] = $this->_real_escape( $v );
812 $data = $this->_real_escape( $data );
819 * Escapes content for insertion into the database using addslashes(), for security.
824 * @param string|array $data to escape
825 * @return string|array escaped as query safe string
827 function escape( $data ) {
828 if ( is_array( $data ) ) {
829 foreach ( (array) $data as $k => $v ) {
830 if ( is_array( $v ) )
831 $data[$k] = $this->escape( $v );
833 $data[$k] = $this->_weak_escape( $v );
836 $data = $this->_weak_escape( $data );
843 * Escapes content by reference for insertion into the database, for security
845 * @uses wpdb::_real_escape()
847 * @param string $string to escape
850 function escape_by_ref( &$string ) {
851 $string = $this->_real_escape( $string );
855 * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
857 * The following directives can be used in the query format string:
861 * %% (literal percentage sign - no argument needed)
863 * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
864 * Literals (%) as parts of the query must be properly written as %%.
866 * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
867 * Does not support sign, padding, alignment, width or precision specifiers.
868 * Does not support argument numbering/swapping.
870 * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
872 * Both %d and %s should be left unquoted in the query string.
875 * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
876 * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
879 * @link http://php.net/sprintf Description of syntax.
882 * @param string $query Query statement with sprintf()-like placeholders
883 * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
884 * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
885 * being called like {@link http://php.net/sprintf sprintf()}.
886 * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
887 * {@link http://php.net/sprintf sprintf()}.
888 * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
889 * if there was something to prepare
891 function prepare( $query = null ) { // ( $query, *$args )
892 if ( is_null( $query ) )
895 $args = func_get_args();
896 array_shift( $args );
897 // If args were passed as an array (as in vsprintf), move them up
898 if ( isset( $args[0] ) && is_array($args[0]) )
900 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
901 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
902 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
903 array_walk( $args, array( &$this, 'escape_by_ref' ) );
904 return @vsprintf( $query, $args );
908 * Print SQL/DB error.
911 * @global array $EZSQL_ERROR Stores error information of query and error string
913 * @param string $str The error to display
914 * @return bool False if the showing of errors is disabled.
916 function print_error( $str = '' ) {
920 $str = mysql_error( $this->dbh );
921 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
923 if ( $this->suppress_errors )
926 if ( $caller = $this->get_caller() )
927 $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 );
929 $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 );
931 if ( function_exists( 'error_log' )
932 && ( $log_file = @ini_get( 'error_log' ) )
933 && ( 'syslog' == $log_file || @is_writable( $log_file ) )
935 @error_log( $error_str );
937 // Are we showing errors?
938 if ( ! $this->show_errors )
941 // If there is an error then take note of it
942 if ( is_multisite() ) {
943 $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
944 if ( defined( 'ERRORLOGFILE' ) )
945 error_log( $msg, 3, ERRORLOGFILE );
946 if ( defined( 'DIEONDBERROR' ) )
949 $str = htmlspecialchars( $str, ENT_QUOTES );
950 $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
952 print "<div id='error'>
953 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
954 <code>$query</code></p>
960 * Enables showing of database errors.
962 * This function should be used only to enable showing of errors.
963 * wpdb::hide_errors() should be used instead for hiding of errors. However,
964 * this function can be used to enable and disable showing of database
968 * @see wpdb::hide_errors()
970 * @param bool $show Whether to show or hide errors
971 * @return bool Old value for showing errors.
973 function show_errors( $show = true ) {
974 $errors = $this->show_errors;
975 $this->show_errors = $show;
980 * Disables showing of database errors.
982 * By default database errors are not shown.
985 * @see wpdb::show_errors()
987 * @return bool Whether showing of errors was active
989 function hide_errors() {
990 $show = $this->show_errors;
991 $this->show_errors = false;
996 * Whether to suppress database errors.
998 * By default database errors are suppressed, with a simple
999 * call to this function they can be enabled.
1002 * @see wpdb::hide_errors()
1003 * @param bool $suppress Optional. New value. Defaults to true.
1004 * @return bool Old value
1006 function suppress_errors( $suppress = true ) {
1007 $errors = $this->suppress_errors;
1008 $this->suppress_errors = (bool) $suppress;
1013 * Kill cached query results.
1019 $this->last_result = array();
1020 $this->col_info = null;
1021 $this->last_query = null;
1025 * Connect to and select database
1029 function db_connect() {
1031 $this->is_mysql = true;
1034 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1036 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, true );
1039 if ( !$this->dbh ) {
1040 $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/"
1041 <h1>Error establishing a database connection</h1>
1042 <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>
1044 <li>Are you sure you have the correct username and password?</li>
1045 <li>Are you sure that you have typed the correct hostname?</li>
1046 <li>Are you sure that the database server is running?</li>
1048 <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>
1049 "/*/WP_I18N_DB_CONN_ERROR*/, htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1054 $this->set_charset( $this->dbh );
1056 $this->ready = true;
1058 $this->select( $this->dbname, $this->dbh );
1062 * Perform a MySQL database query, using current database connection.
1064 * More information can be found on the codex page.
1068 * @param string $query Database query
1069 * @return int|false Number of rows affected/selected or false on error
1071 function query( $query ) {
1072 if ( ! $this->ready )
1075 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1076 if ( function_exists( 'apply_filters' ) )
1077 $query = apply_filters( 'query', $query );
1082 // Log how the function was called
1083 $this->func_call = "\$db->query(\"$query\")";
1085 // Keep track of the last query for debug..
1086 $this->last_query = $query;
1088 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1089 $this->timer_start();
1091 $this->result = @mysql_query( $query, $this->dbh );
1092 $this->num_queries++;
1094 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1095 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1097 // If there is an error then take note of it..
1098 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1099 $this->print_error();
1103 if ( preg_match( '/^\s*(create|alter|truncate|drop) /i', $query ) ) {
1104 $return_val = $this->result;
1105 } elseif ( preg_match( '/^\s*(insert|delete|update|replace) /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', '%f', '%s' (integer, float, 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', '%f', '%s' (integer, float, 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', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1197 * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1198 * @return int|false The number of rows affected, or false on error.
1200 function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1201 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1203 $formats = $format = (array) $format;
1204 $fields = array_keys( $data );
1205 $formatted_fields = array();
1206 foreach ( $fields as $field ) {
1207 if ( !empty( $format ) )
1208 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1209 elseif ( isset( $this->field_types[$field] ) )
1210 $form = $this->field_types[$field];
1213 $formatted_fields[] = $form;
1215 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
1216 return $this->query( $this->prepare( $sql, $data ) );
1220 * Update a row in the table
1223 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1224 * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1228 * @see wpdb::prepare()
1229 * @see wpdb::$field_types
1230 * @see wp_set_wpdb_vars()
1232 * @param string $table table name
1233 * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1234 * @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".
1235 * @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.
1236 * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1237 * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings.
1238 * @return int|false The number of rows updated, or false on error.
1240 function update( $table, $data, $where, $format = null, $where_format = null ) {
1241 if ( ! is_array( $data ) || ! is_array( $where ) )
1244 $formats = $format = (array) $format;
1245 $bits = $wheres = array();
1246 foreach ( (array) array_keys( $data ) as $field ) {
1247 if ( !empty( $format ) )
1248 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1249 elseif ( isset($this->field_types[$field]) )
1250 $form = $this->field_types[$field];
1253 $bits[] = "`$field` = {$form}";
1256 $where_formats = $where_format = (array) $where_format;
1257 foreach ( (array) array_keys( $where ) as $field ) {
1258 if ( !empty( $where_format ) )
1259 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1260 elseif ( isset( $this->field_types[$field] ) )
1261 $form = $this->field_types[$field];
1264 $wheres[] = "`$field` = {$form}";
1267 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1268 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1272 * Retrieve one variable from the database.
1274 * Executes a SQL query and returns the value from the SQL result.
1275 * 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.
1276 * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1280 * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1281 * @param int $x Optional. Column of value to return. Indexed from 0.
1282 * @param int $y Optional. Row of value to return. Indexed from 0.
1283 * @return string|null Database query result (as string), or null on failure
1285 function get_var( $query = null, $x = 0, $y = 0 ) {
1286 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1288 $this->query( $query );
1290 // Extract var out of cached results based x,y vals
1291 if ( !empty( $this->last_result[$y] ) ) {
1292 $values = array_values( get_object_vars( $this->last_result[$y] ) );
1295 // If there is a value return it else return null
1296 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1300 * Retrieve one row from the database.
1302 * Executes a SQL query and returns the row from the SQL result.
1306 * @param string|null $query SQL query.
1307 * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1308 * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1309 * @param int $y Optional. Row to return. Indexed from 0.
1310 * @return mixed Database query result in format specified by $output or null on failure
1312 function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1313 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1315 $this->query( $query );
1319 if ( !isset( $this->last_result[$y] ) )
1322 if ( $output == OBJECT ) {
1323 return $this->last_result[$y] ? $this->last_result[$y] : null;
1324 } elseif ( $output == ARRAY_A ) {
1325 return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1326 } elseif ( $output == ARRAY_N ) {
1327 return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1329 $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*/);
1334 * Retrieve one column from the database.
1336 * Executes a SQL query and returns the column from the SQL result.
1337 * If the SQL result contains more than one column, this function returns the column specified.
1338 * If $query is null, this function returns the specified column from the previous SQL result.
1342 * @param string|null $query Optional. SQL query. Defaults to previous query.
1343 * @param int $x Optional. Column to return. Indexed from 0.
1344 * @return array Database query result. Array indexed from 0 by SQL result row number.
1346 function get_col( $query = null , $x = 0 ) {
1348 $this->query( $query );
1350 $new_array = array();
1351 // Extract the column values
1352 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1353 $new_array[$i] = $this->get_var( null, $x, $i );
1359 * Retrieve an entire SQL result set from the database (i.e., many rows)
1361 * Executes a SQL query and returns the entire SQL result.
1365 * @param string $query SQL query.
1366 * @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.
1367 * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1368 * 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.
1369 * @return mixed Database query results
1371 function get_results( $query = null, $output = OBJECT ) {
1372 $this->func_call = "\$db->get_results(\"$query\", $output)";
1375 $this->query( $query );
1379 $new_array = array();
1380 if ( $output == OBJECT ) {
1381 // Return an integer-keyed array of row objects
1382 return $this->last_result;
1383 } elseif ( $output == OBJECT_K ) {
1384 // Return an array of row objects with keys from column 1
1385 // (Duplicates are discarded)
1386 foreach ( $this->last_result as $row ) {
1387 $var_by_ref = get_object_vars( $row );
1388 $key = array_shift( $var_by_ref );
1389 if ( ! isset( $new_array[ $key ] ) )
1390 $new_array[ $key ] = $row;
1393 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1394 // Return an integer-keyed array of...
1395 if ( $this->last_result ) {
1396 foreach( (array) $this->last_result as $row ) {
1397 if ( $output == ARRAY_N ) {
1398 // ...integer-keyed row arrays
1399 $new_array[] = array_values( get_object_vars( $row ) );
1401 // ...column name-keyed row arrays
1402 $new_array[] = get_object_vars( $row );
1412 * Retrieve column metadata from the last query.
1416 * @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
1417 * @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
1418 * @return mixed Column Results
1420 function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1421 if ( $this->col_info ) {
1422 if ( $col_offset == -1 ) {
1424 $new_array = array();
1425 foreach( (array) $this->col_info as $col ) {
1426 $new_array[$i] = $col->{$info_type};
1431 return $this->col_info[$col_offset]->{$info_type};
1437 * Starts the timer, for debugging purposes.
1443 function timer_start() {
1444 $mtime = explode( ' ', microtime() );
1445 $this->time_start = $mtime[1] + $mtime[0];
1450 * Stops the debugging timer.
1454 * @return int Total time spent on the query, in milliseconds
1456 function timer_stop() {
1457 $mtime = explode( ' ', microtime() );
1458 $time_end = $mtime[1] + $mtime[0];
1459 $time_total = $time_end - $this->time_start;
1464 * Wraps errors in a nice header and footer and dies.
1466 * Will not die if wpdb::$show_errors is true
1470 * @param string $message The Error message
1471 * @param string $error_code Optional. A Computer readable string to identify the error.
1472 * @return false|void
1474 function bail( $message, $error_code = '500' ) {
1475 if ( !$this->show_errors ) {
1476 if ( class_exists( 'WP_Error' ) )
1477 $this->error = new WP_Error($error_code, $message);
1479 $this->error = $message;
1486 * Whether MySQL database is at least the required minimum version.
1490 * @uses $required_mysql_version
1494 function check_database_version() {
1495 global $wp_version, $required_mysql_version;
1496 // Make sure the server has the required MySQL version
1497 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1498 return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1502 * Whether the database supports collation.
1504 * Called when WordPress is generating the table scheme.
1508 * @return bool True if collation is supported, false if version does not
1510 function supports_collation() {
1511 return $this->has_cap( 'collation' );
1515 * Determine if a database supports a particular feature
1518 * @see wpdb::db_version()
1520 * @param string $db_cap the feature
1523 function has_cap( $db_cap ) {
1524 $version = $this->db_version();
1526 switch ( strtolower( $db_cap ) ) {
1527 case 'collation' : // @since 2.5.0
1528 case 'group_concat' : // @since 2.7
1529 case 'subqueries' : // @since 2.7
1530 return version_compare( $version, '4.1', '>=' );
1531 case 'set_charset' :
1532 return version_compare($version, '5.0.7', '>=');
1539 * Retrieve the name of the function that called wpdb.
1541 * Searches up the list of functions until it reaches
1542 * the one that would most logically had called this method.
1546 * @return string The name of the calling function
1548 function get_caller() {
1549 $trace = array_reverse( debug_backtrace() );
1552 foreach ( $trace as $call ) {
1553 if ( isset( $call['class'] ) && __CLASS__ == $call['class'] )
1554 continue; // Filter out wpdb calls.
1555 $caller[] = isset( $call['class'] ) ? "{$call['class']}->{$call['function']}" : $call['function'];
1558 return join( ', ', $caller );
1562 * The database version number.
1566 * @return false|string false on failure, version number on success
1568 function db_version() {
1569 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );