]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/wp-db.php
Wordpress 3.5.2-scripts
[autoinstalls/wordpress.git] / wp-includes / wp-db.php
1 <?php
2 /**
3  * WordPress DB Class
4  *
5  * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
6  *
7  * @package WordPress
8  * @subpackage Database
9  * @since 0.71
10  */
11
12 /**
13  * @since 0.71
14  */
15 define( 'EZSQL_VERSION', 'WP1.25' );
16
17 /**
18  * @since 0.71
19  */
20 define( 'OBJECT', 'OBJECT', true );
21
22 /**
23  * @since 2.5.0
24  */
25 define( 'OBJECT_K', 'OBJECT_K' );
26
27 /**
28  * @since 0.71
29  */
30 define( 'ARRAY_A', 'ARRAY_A' );
31
32 /**
33  * @since 0.71
34  */
35 define( 'ARRAY_N', 'ARRAY_N' );
36
37 /**
38  * WordPress Database Access Abstraction Object
39  *
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.
44  *
45  * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
46  *
47  * @package WordPress
48  * @subpackage Database
49  * @since 0.71
50  */
51 class wpdb {
52
53         /**
54          * Whether to show SQL/DB errors
55          *
56          * @since 0.71
57          * @access private
58          * @var bool
59          */
60         var $show_errors = false;
61
62         /**
63          * Whether to suppress errors during the DB bootstrapping.
64          *
65          * @access private
66          * @since 2.5.0
67          * @var bool
68          */
69         var $suppress_errors = false;
70
71         /**
72          * The last error during query.
73          *
74          * @since 2.5.0
75          * @var string
76          */
77         var $last_error = '';
78
79         /**
80          * Amount of queries made
81          *
82          * @since 1.2.0
83          * @access private
84          * @var int
85          */
86         var $num_queries = 0;
87
88         /**
89          * Count of rows returned by previous query
90          *
91          * @since 0.71
92          * @access private
93          * @var int
94          */
95         var $num_rows = 0;
96
97         /**
98          * Count of affected rows by previous query
99          *
100          * @since 0.71
101          * @access private
102          * @var int
103          */
104         var $rows_affected = 0;
105
106         /**
107          * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
108          *
109          * @since 0.71
110          * @access public
111          * @var int
112          */
113         var $insert_id = 0;
114
115         /**
116          * Last query made
117          *
118          * @since 0.71
119          * @access private
120          * @var array
121          */
122         var $last_query;
123
124         /**
125          * Results of the last query made
126          *
127          * @since 0.71
128          * @access private
129          * @var array|null
130          */
131         var $last_result;
132
133         /**
134          * MySQL result, which is either a resource or boolean.
135          *
136          * @since 0.71
137          * @access protected
138          * @var mixed
139          */
140         protected $result;
141
142         /**
143          * Saved info on the table column
144          *
145          * @since 0.71
146          * @access protected
147          * @var array
148          */
149         protected $col_info;
150
151         /**
152          * Saved queries that were executed
153          *
154          * @since 1.5.0
155          * @access private
156          * @var array
157          */
158         var $queries;
159
160         /**
161          * WordPress table prefix
162          *
163          * You can set this to have multiple WordPress installations
164          * in a single database. The second reason is for possible
165          * security precautions.
166          *
167          * @since 2.5.0
168          * @access private
169          * @var string
170          */
171         var $prefix = '';
172
173         /**
174          * Whether the database queries are ready to start executing.
175          *
176          * @since 2.3.2
177          * @access private
178          * @var bool
179          */
180         var $ready = false;
181
182         /**
183          * {@internal Missing Description}}
184          *
185          * @since 3.0.0
186          * @access public
187          * @var int
188          */
189         var $blogid = 0;
190
191         /**
192          * {@internal Missing Description}}
193          *
194          * @since 3.0.0
195          * @access public
196          * @var int
197          */
198         var $siteid = 0;
199
200         /**
201          * List of WordPress per-blog tables
202          *
203          * @since 2.5.0
204          * @access private
205          * @see wpdb::tables()
206          * @var array
207          */
208         var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
209                 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
210
211         /**
212          * List of deprecated WordPress tables
213          *
214          * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
215          *
216          * @since 2.9.0
217          * @access private
218          * @see wpdb::tables()
219          * @var array
220          */
221         var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
222
223         /**
224          * List of WordPress global tables
225          *
226          * @since 3.0.0
227          * @access private
228          * @see wpdb::tables()
229          * @var array
230          */
231         var $global_tables = array( 'users', 'usermeta' );
232
233         /**
234          * List of Multisite global tables
235          *
236          * @since 3.0.0
237          * @access private
238          * @see wpdb::tables()
239          * @var array
240          */
241         var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
242                 'sitecategories', 'registration_log', 'blog_versions' );
243
244         /**
245          * WordPress Comments table
246          *
247          * @since 1.5.0
248          * @access public
249          * @var string
250          */
251         var $comments;
252
253         /**
254          * WordPress Comment Metadata table
255          *
256          * @since 2.9.0
257          * @access public
258          * @var string
259          */
260         var $commentmeta;
261
262         /**
263          * WordPress Links table
264          *
265          * @since 1.5.0
266          * @access public
267          * @var string
268          */
269         var $links;
270
271         /**
272          * WordPress Options table
273          *
274          * @since 1.5.0
275          * @access public
276          * @var string
277          */
278         var $options;
279
280         /**
281          * WordPress Post Metadata table
282          *
283          * @since 1.5.0
284          * @access public
285          * @var string
286          */
287         var $postmeta;
288
289         /**
290          * WordPress Posts table
291          *
292          * @since 1.5.0
293          * @access public
294          * @var string
295          */
296         var $posts;
297
298         /**
299          * WordPress Terms table
300          *
301          * @since 2.3.0
302          * @access public
303          * @var string
304          */
305         var $terms;
306
307         /**
308          * WordPress Term Relationships table
309          *
310          * @since 2.3.0
311          * @access public
312          * @var string
313          */
314         var $term_relationships;
315
316         /**
317          * WordPress Term Taxonomy table
318          *
319          * @since 2.3.0
320          * @access public
321          * @var string
322          */
323         var $term_taxonomy;
324
325         /*
326          * Global and Multisite tables
327          */
328
329         /**
330          * WordPress User Metadata table
331          *
332          * @since 2.3.0
333          * @access public
334          * @var string
335          */
336         var $usermeta;
337
338         /**
339          * WordPress Users table
340          *
341          * @since 1.5.0
342          * @access public
343          * @var string
344          */
345         var $users;
346
347         /**
348          * Multisite Blogs table
349          *
350          * @since 3.0.0
351          * @access public
352          * @var string
353          */
354         var $blogs;
355
356         /**
357          * Multisite Blog Versions table
358          *
359          * @since 3.0.0
360          * @access public
361          * @var string
362          */
363         var $blog_versions;
364
365         /**
366          * Multisite Registration Log table
367          *
368          * @since 3.0.0
369          * @access public
370          * @var string
371          */
372         var $registration_log;
373
374         /**
375          * Multisite Signups table
376          *
377          * @since 3.0.0
378          * @access public
379          * @var string
380          */
381         var $signups;
382
383         /**
384          * Multisite Sites table
385          *
386          * @since 3.0.0
387          * @access public
388          * @var string
389          */
390         var $site;
391
392         /**
393          * Multisite Sitewide Terms table
394          *
395          * @since 3.0.0
396          * @access public
397          * @var string
398          */
399         var $sitecategories;
400
401         /**
402          * Multisite Site Metadata table
403          *
404          * @since 3.0.0
405          * @access public
406          * @var string
407          */
408         var $sitemeta;
409
410         /**
411          * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
412          *
413          * Keys are column names, values are format types: 'ID' => '%d'
414          *
415          * @since 2.8.0
416          * @see wpdb::prepare()
417          * @see wpdb::insert()
418          * @see wpdb::update()
419          * @see wpdb::delete()
420          * @see wp_set_wpdb_vars()
421          * @access public
422          * @var array
423          */
424         var $field_types = array();
425
426         /**
427          * Database table columns charset
428          *
429          * @since 2.2.0
430          * @access public
431          * @var string
432          */
433         var $charset;
434
435         /**
436          * Database table columns collate
437          *
438          * @since 2.2.0
439          * @access public
440          * @var string
441          */
442         var $collate;
443
444         /**
445          * Whether to use mysql_real_escape_string
446          *
447          * @since 2.8.0
448          * @access public
449          * @var bool
450          */
451         var $real_escape = false;
452
453         /**
454          * Database Username
455          *
456          * @since 2.9.0
457          * @access protected
458          * @var string
459          */
460         protected $dbuser;
461
462         /**
463          * Database Password
464          *
465          * @since 3.1.0
466          * @access protected
467          * @var string
468          */
469         protected $dbpassword;
470
471         /**
472          * Database Name
473          *
474          * @since 3.1.0
475          * @access protected
476          * @var string
477          */
478         protected $dbname;
479
480         /**
481          * Database Host
482          *
483          * @since 3.1.0
484          * @access protected
485          * @var string
486          */
487         protected $dbhost;
488
489         /**
490          * Database Handle
491          *
492          * @since 0.71
493          * @access protected
494          * @var string
495          */
496         protected $dbh;
497
498         /**
499          * A textual description of the last query/get_row/get_var call
500          *
501          * @since 3.0.0
502          * @access public
503          * @var string
504          */
505         var $func_call;
506
507         /**
508          * Whether MySQL is used as the database engine.
509          *
510          * Set in WPDB::db_connect() to true, by default. This is used when checking
511          * against the required MySQL version for WordPress. Normally, a replacement
512          * database drop-in (db.php) will skip these checks, but setting this to true
513          * will force the checks to occur.
514          *
515          * @since 3.3.0
516          * @access public
517          * @var bool
518          */
519         public $is_mysql = null;
520
521         /**
522          * Connects to the database server and selects a database
523          *
524          * PHP5 style constructor for compatibility with PHP5. Does
525          * the actual setting up of the class properties and connection
526          * to the database.
527          *
528          * @link http://core.trac.wordpress.org/ticket/3354
529          * @since 2.0.8
530          *
531          * @param string $dbuser MySQL database user
532          * @param string $dbpassword MySQL database password
533          * @param string $dbname MySQL database name
534          * @param string $dbhost MySQL database host
535          */
536         function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
537                 register_shutdown_function( array( $this, '__destruct' ) );
538
539                 if ( WP_DEBUG )
540                         $this->show_errors();
541
542                 $this->init_charset();
543
544                 $this->dbuser = $dbuser;
545                 $this->dbpassword = $dbpassword;
546                 $this->dbname = $dbname;
547                 $this->dbhost = $dbhost;
548
549                 $this->db_connect();
550         }
551
552         /**
553          * PHP5 style destructor and will run when database object is destroyed.
554          *
555          * @see wpdb::__construct()
556          * @since 2.0.8
557          * @return bool true
558          */
559         function __destruct() {
560                 return true;
561         }
562
563         /**
564          * PHP5 style magic getter, used to lazy-load expensive data.
565          *
566          * @since 3.5.0
567          *
568          * @param string $name The private member to get, and optionally process
569          * @return mixed The private member
570          */
571         function __get( $name ) {
572                 if ( 'col_info' == $name )
573                         $this->load_col_info();
574
575                 return $this->$name;
576         }
577
578         /**
579          * Magic function, for backwards compatibility
580          *
581          * @since 3.5.0
582          *
583          * @param string $name  The private member to set
584          * @param mixed  $value The value to set
585          */
586         function __set( $name, $value ) {
587                 $this->$name = $value;
588         }
589
590         /**
591          * Magic function, for backwards compatibility
592          *
593          * @since 3.5.0
594          *
595          * @param string $name  The private member to check
596          *
597          * @return bool If the member is set or not
598          */
599         function __isset( $name ) {
600                 return isset( $this->$name );
601         }
602
603         /**
604          * Magic function, for backwards compatibility
605          *
606          * @since 3.5.0
607          *
608          * @param string $name  The private member to unset
609          */
610         function __unset( $name ) {
611                 unset( $this->$name );
612         }
613
614         /**
615          * Set $this->charset and $this->collate
616          *
617          * @since 3.1.0
618          */
619         function init_charset() {
620                 if ( function_exists('is_multisite') && is_multisite() ) {
621                         $this->charset = 'utf8';
622                         if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
623                                 $this->collate = DB_COLLATE;
624                         else
625                                 $this->collate = 'utf8_general_ci';
626                 } elseif ( defined( 'DB_COLLATE' ) ) {
627                         $this->collate = DB_COLLATE;
628                 }
629
630                 if ( defined( 'DB_CHARSET' ) )
631                         $this->charset = DB_CHARSET;
632         }
633
634         /**
635          * Sets the connection's character set.
636          *
637          * @since 3.1.0
638          *
639          * @param resource $dbh     The resource given by mysql_connect
640          * @param string   $charset The character set (optional)
641          * @param string   $collate The collation (optional)
642          */
643         function set_charset($dbh, $charset = null, $collate = null) {
644                 if ( !isset($charset) )
645                         $charset = $this->charset;
646                 if ( !isset($collate) )
647                         $collate = $this->collate;
648                 if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
649                         if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
650                                 mysql_set_charset( $charset, $dbh );
651                                 $this->real_escape = true;
652                         } else {
653                                 $query = $this->prepare( 'SET NAMES %s', $charset );
654                                 if ( ! empty( $collate ) )
655                                         $query .= $this->prepare( ' COLLATE %s', $collate );
656                                 mysql_query( $query, $dbh );
657                         }
658                 }
659         }
660
661         /**
662          * Sets the table prefix for the WordPress tables.
663          *
664          * @since 2.5.0
665          *
666          * @param string $prefix Alphanumeric name for the new prefix.
667          * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
668          * @return string|WP_Error Old prefix or WP_Error on error
669          */
670         function set_prefix( $prefix, $set_table_names = true ) {
671
672                 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
673                         return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
674
675                 $old_prefix = is_multisite() ? '' : $prefix;
676
677                 if ( isset( $this->base_prefix ) )
678                         $old_prefix = $this->base_prefix;
679
680                 $this->base_prefix = $prefix;
681
682                 if ( $set_table_names ) {
683                         foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
684                                 $this->$table = $prefixed_table;
685
686                         if ( is_multisite() && empty( $this->blogid ) )
687                                 return $old_prefix;
688
689                         $this->prefix = $this->get_blog_prefix();
690
691                         foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
692                                 $this->$table = $prefixed_table;
693
694                         foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
695                                 $this->$table = $prefixed_table;
696                 }
697                 return $old_prefix;
698         }
699
700         /**
701          * Sets blog id.
702          *
703          * @since 3.0.0
704          * @access public
705          * @param int $blog_id
706          * @param int $site_id Optional.
707          * @return string previous blog id
708          */
709         function set_blog_id( $blog_id, $site_id = 0 ) {
710                 if ( ! empty( $site_id ) )
711                         $this->siteid = $site_id;
712
713                 $old_blog_id  = $this->blogid;
714                 $this->blogid = $blog_id;
715
716                 $this->prefix = $this->get_blog_prefix();
717
718                 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
719                         $this->$table = $prefixed_table;
720
721                 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
722                         $this->$table = $prefixed_table;
723
724                 return $old_blog_id;
725         }
726
727         /**
728          * Gets blog prefix.
729          *
730          * @uses is_multisite()
731          * @since 3.0.0
732          * @param int $blog_id Optional.
733          * @return string Blog prefix.
734          */
735         function get_blog_prefix( $blog_id = null ) {
736                 if ( is_multisite() ) {
737                         if ( null === $blog_id )
738                                 $blog_id = $this->blogid;
739                         $blog_id = (int) $blog_id;
740                         if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
741                                 return $this->base_prefix;
742                         else
743                                 return $this->base_prefix . $blog_id . '_';
744                 } else {
745                         return $this->base_prefix;
746                 }
747         }
748
749         /**
750          * Returns an array of WordPress tables.
751          *
752          * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
753          * override the WordPress users and usermeta tables that would otherwise
754          * be determined by the prefix.
755          *
756          * The scope argument can take one of the following:
757          *
758          * 'all' - returns 'all' and 'global' tables. No old tables are returned.
759          * 'blog' - returns the blog-level tables for the queried blog.
760          * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
761          * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
762          * 'old' - returns tables which are deprecated.
763          *
764          * @since 3.0.0
765          * @uses wpdb::$tables
766          * @uses wpdb::$old_tables
767          * @uses wpdb::$global_tables
768          * @uses wpdb::$ms_global_tables
769          * @uses is_multisite()
770          *
771          * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
772          * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
773          *      prefix is requested, then the custom users and usermeta tables will be mapped.
774          * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
775          * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
776          */
777         function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
778                 switch ( $scope ) {
779                         case 'all' :
780                                 $tables = array_merge( $this->global_tables, $this->tables );
781                                 if ( is_multisite() )
782                                         $tables = array_merge( $tables, $this->ms_global_tables );
783                                 break;
784                         case 'blog' :
785                                 $tables = $this->tables;
786                                 break;
787                         case 'global' :
788                                 $tables = $this->global_tables;
789                                 if ( is_multisite() )
790                                         $tables = array_merge( $tables, $this->ms_global_tables );
791                                 break;
792                         case 'ms_global' :
793                                 $tables = $this->ms_global_tables;
794                                 break;
795                         case 'old' :
796                                 $tables = $this->old_tables;
797                                 break;
798                         default :
799                                 return array();
800                                 break;
801                 }
802
803                 if ( $prefix ) {
804                         if ( ! $blog_id )
805                                 $blog_id = $this->blogid;
806                         $blog_prefix = $this->get_blog_prefix( $blog_id );
807                         $base_prefix = $this->base_prefix;
808                         $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
809                         foreach ( $tables as $k => $table ) {
810                                 if ( in_array( $table, $global_tables ) )
811                                         $tables[ $table ] = $base_prefix . $table;
812                                 else
813                                         $tables[ $table ] = $blog_prefix . $table;
814                                 unset( $tables[ $k ] );
815                         }
816
817                         if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
818                                 $tables['users'] = CUSTOM_USER_TABLE;
819
820                         if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
821                                 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
822                 }
823
824                 return $tables;
825         }
826
827         /**
828          * Selects a database using the current database connection.
829          *
830          * The database name will be changed based on the current database
831          * connection. On failure, the execution will bail and display an DB error.
832          *
833          * @since 0.71
834          *
835          * @param string $db MySQL database name
836          * @param resource $dbh Optional link identifier.
837          * @return null Always null.
838          */
839         function select( $db, $dbh = null ) {
840                 if ( is_null($dbh) )
841                         $dbh = $this->dbh;
842
843                 if ( !@mysql_select_db( $db, $dbh ) ) {
844                         $this->ready = false;
845                         wp_load_translations_early();
846                         $this->bail( sprintf( __( '<h1>Can&#8217;t select database</h1>
847 <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>
848 <ul>
849 <li>Are you sure it exists?</li>
850 <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
851 <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>
852 </ul>
853 <p>If you don\'t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="http://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
854                         return;
855                 }
856         }
857
858         /**
859          * Weak escape, using addslashes()
860          *
861          * @see addslashes()
862          * @since 2.8.0
863          * @access private
864          *
865          * @param string $string
866          * @return string
867          */
868         function _weak_escape( $string ) {
869                 return addslashes( $string );
870         }
871
872         /**
873          * Real escape, using mysql_real_escape_string() or addslashes()
874          *
875          * @see mysql_real_escape_string()
876          * @see addslashes()
877          * @since 2.8.0
878          * @access private
879          *
880          * @param  string $string to escape
881          * @return string escaped
882          */
883         function _real_escape( $string ) {
884                 if ( $this->dbh && $this->real_escape )
885                         return mysql_real_escape_string( $string, $this->dbh );
886                 else
887                         return addslashes( $string );
888         }
889
890         /**
891          * Escape data. Works on arrays.
892          *
893          * @uses wpdb::_escape()
894          * @uses wpdb::_real_escape()
895          * @since  2.8.0
896          * @access private
897          *
898          * @param  string|array $data
899          * @return string|array escaped
900          */
901         function _escape( $data ) {
902                 if ( is_array( $data ) ) {
903                         foreach ( (array) $data as $k => $v ) {
904                                 if ( is_array($v) )
905                                         $data[$k] = $this->_escape( $v );
906                                 else
907                                         $data[$k] = $this->_real_escape( $v );
908                         }
909                 } else {
910                         $data = $this->_real_escape( $data );
911                 }
912
913                 return $data;
914         }
915
916         /**
917          * Escapes content for insertion into the database using addslashes(), for security.
918          *
919          * Works on arrays.
920          *
921          * @since 0.71
922          * @param string|array $data to escape
923          * @return string|array escaped as query safe string
924          */
925         function escape( $data ) {
926                 if ( is_array( $data ) ) {
927                         foreach ( (array) $data as $k => $v ) {
928                                 if ( is_array( $v ) )
929                                         $data[$k] = $this->escape( $v );
930                                 else
931                                         $data[$k] = $this->_weak_escape( $v );
932                         }
933                 } else {
934                         $data = $this->_weak_escape( $data );
935                 }
936
937                 return $data;
938         }
939
940         /**
941          * Escapes content by reference for insertion into the database, for security
942          *
943          * @uses wpdb::_real_escape()
944          * @since 2.3.0
945          * @param string $string to escape
946          * @return void
947          */
948         function escape_by_ref( &$string ) {
949                 if ( ! is_float( $string ) )
950                         $string = $this->_real_escape( $string );
951         }
952
953         /**
954          * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
955          *
956          * The following directives can be used in the query format string:
957          *   %d (integer)
958          *   %f (float)
959          *   %s (string)
960          *   %% (literal percentage sign - no argument needed)
961          *
962          * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
963          * Literals (%) as parts of the query must be properly written as %%.
964          *
965          * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
966          * Does not support sign, padding, alignment, width or precision specifiers.
967          * Does not support argument numbering/swapping.
968          *
969          * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
970          *
971          * Both %d and %s should be left unquoted in the query string.
972          *
973          * <code>
974          * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
975          * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
976          * </code>
977          *
978          * @link http://php.net/sprintf Description of syntax.
979          * @since 2.3.0
980          *
981          * @param string $query Query statement with sprintf()-like placeholders
982          * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
983          *      {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
984          *      being called like {@link http://php.net/sprintf sprintf()}.
985          * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
986          *      {@link http://php.net/sprintf sprintf()}.
987          * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
988          *      if there was something to prepare
989          */
990         function prepare( $query, $args = null ) {
991                 if ( is_null( $query ) )
992                         return;
993
994                 if ( func_num_args() < 2 )
995                         _doing_it_wrong( 'wpdb::prepare', 'wpdb::prepare() requires at least two arguments.', '3.5' );
996
997                 $args = func_get_args();
998                 array_shift( $args );
999                 // If args were passed as an array (as in vsprintf), move them up
1000                 if ( isset( $args[0] ) && is_array($args[0]) )
1001                         $args = $args[0];
1002                 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1003                 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1004                 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1005                 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1006                 array_walk( $args, array( $this, 'escape_by_ref' ) );
1007                 return @vsprintf( $query, $args );
1008         }
1009
1010         /**
1011          * Print SQL/DB error.
1012          *
1013          * @since 0.71
1014          * @global array $EZSQL_ERROR Stores error information of query and error string
1015          *
1016          * @param string $str The error to display
1017          * @return bool False if the showing of errors is disabled.
1018          */
1019         function print_error( $str = '' ) {
1020                 global $EZSQL_ERROR;
1021
1022                 if ( !$str )
1023                         $str = mysql_error( $this->dbh );
1024                 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1025
1026                 if ( $this->suppress_errors )
1027                         return false;
1028
1029                 wp_load_translations_early();
1030
1031                 if ( $caller = $this->get_caller() )
1032                         $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1033                 else
1034                         $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1035
1036                 error_log( $error_str );
1037
1038                 // Are we showing errors?
1039                 if ( ! $this->show_errors )
1040                         return false;
1041
1042                 // If there is an error then take note of it
1043                 if ( is_multisite() ) {
1044                         $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
1045                         if ( defined( 'ERRORLOGFILE' ) )
1046                                 error_log( $msg, 3, ERRORLOGFILE );
1047                         if ( defined( 'DIEONDBERROR' ) )
1048                                 wp_die( $msg );
1049                 } else {
1050                         $str   = htmlspecialchars( $str, ENT_QUOTES );
1051                         $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1052
1053                         print "<div id='error'>
1054                         <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
1055                         <code>$query</code></p>
1056                         </div>";
1057                 }
1058         }
1059
1060         /**
1061          * Enables showing of database errors.
1062          *
1063          * This function should be used only to enable showing of errors.
1064          * wpdb::hide_errors() should be used instead for hiding of errors. However,
1065          * this function can be used to enable and disable showing of database
1066          * errors.
1067          *
1068          * @since 0.71
1069          * @see wpdb::hide_errors()
1070          *
1071          * @param bool $show Whether to show or hide errors
1072          * @return bool Old value for showing errors.
1073          */
1074         function show_errors( $show = true ) {
1075                 $errors = $this->show_errors;
1076                 $this->show_errors = $show;
1077                 return $errors;
1078         }
1079
1080         /**
1081          * Disables showing of database errors.
1082          *
1083          * By default database errors are not shown.
1084          *
1085          * @since 0.71
1086          * @see wpdb::show_errors()
1087          *
1088          * @return bool Whether showing of errors was active
1089          */
1090         function hide_errors() {
1091                 $show = $this->show_errors;
1092                 $this->show_errors = false;
1093                 return $show;
1094         }
1095
1096         /**
1097          * Whether to suppress database errors.
1098          *
1099          * By default database errors are suppressed, with a simple
1100          * call to this function they can be enabled.
1101          *
1102          * @since 2.5.0
1103          * @see wpdb::hide_errors()
1104          * @param bool $suppress Optional. New value. Defaults to true.
1105          * @return bool Old value
1106          */
1107         function suppress_errors( $suppress = true ) {
1108                 $errors = $this->suppress_errors;
1109                 $this->suppress_errors = (bool) $suppress;
1110                 return $errors;
1111         }
1112
1113         /**
1114          * Kill cached query results.
1115          *
1116          * @since 0.71
1117          * @return void
1118          */
1119         function flush() {
1120                 $this->last_result = array();
1121                 $this->col_info    = null;
1122                 $this->last_query  = null;
1123                 $this->rows_affected = $this->num_rows = 0;
1124                 $this->last_error  = '';
1125
1126                 if ( is_resource( $this->result ) )
1127                         mysql_free_result( $this->result );
1128         }
1129
1130         /**
1131          * Connect to and select database
1132          *
1133          * @since 3.0.0
1134          */
1135         function db_connect() {
1136
1137                 $this->is_mysql = true;
1138
1139                 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1140                 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1141
1142                 if ( WP_DEBUG ) {
1143                         $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1144                 } else {
1145                         $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1146                 }
1147
1148                 if ( !$this->dbh ) {
1149                         wp_load_translations_early();
1150                         $this->bail( sprintf( __( "
1151 <h1>Error establishing a database connection</h1>
1152 <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>
1153 <ul>
1154         <li>Are you sure you have the correct username and password?</li>
1155         <li>Are you sure that you have typed the correct hostname?</li>
1156         <li>Are you sure that the database server is running?</li>
1157 </ul>
1158 <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>
1159 " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
1160
1161                         return;
1162                 }
1163
1164                 $this->set_charset( $this->dbh );
1165
1166                 $this->ready = true;
1167
1168                 $this->select( $this->dbname, $this->dbh );
1169         }
1170
1171         /**
1172          * Perform a MySQL database query, using current database connection.
1173          *
1174          * More information can be found on the codex page.
1175          *
1176          * @since 0.71
1177          *
1178          * @param string $query Database query
1179          * @return int|false Number of rows affected/selected or false on error
1180          */
1181         function query( $query ) {
1182                 if ( ! $this->ready )
1183                         return false;
1184
1185                 // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
1186                 $query = apply_filters( 'query', $query );
1187
1188                 $return_val = 0;
1189                 $this->flush();
1190
1191                 // Log how the function was called
1192                 $this->func_call = "\$db->query(\"$query\")";
1193
1194                 // Keep track of the last query for debug..
1195                 $this->last_query = $query;
1196
1197                 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1198                         $this->timer_start();
1199
1200                 $this->result = @mysql_query( $query, $this->dbh );
1201                 $this->num_queries++;
1202
1203                 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
1204                         $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1205
1206                 // If there is an error then take note of it..
1207                 if ( $this->last_error = mysql_error( $this->dbh ) ) {
1208                         $this->print_error();
1209                         return false;
1210                 }
1211
1212                 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1213                         $return_val = $this->result;
1214                 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1215                         $this->rows_affected = mysql_affected_rows( $this->dbh );
1216                         // Take note of the insert_id
1217                         if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1218                                 $this->insert_id = mysql_insert_id($this->dbh);
1219                         }
1220                         // Return number of rows affected
1221                         $return_val = $this->rows_affected;
1222                 } else {
1223                         $num_rows = 0;
1224                         while ( $row = @mysql_fetch_object( $this->result ) ) {
1225                                 $this->last_result[$num_rows] = $row;
1226                                 $num_rows++;
1227                         }
1228
1229                         // Log number of rows the query returned
1230                         // and return number of rows selected
1231                         $this->num_rows = $num_rows;
1232                         $return_val     = $num_rows;
1233                 }
1234
1235                 return $return_val;
1236         }
1237
1238         /**
1239          * Insert a row into a table.
1240          *
1241          * <code>
1242          * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1243          * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1244          * </code>
1245          *
1246          * @since 2.5.0
1247          * @see wpdb::prepare()
1248          * @see wpdb::$field_types
1249          * @see wp_set_wpdb_vars()
1250          *
1251          * @param string $table table name
1252          * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1253          * @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.
1254          *      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.
1255          * @return int|false The number of rows inserted, or false on error.
1256          */
1257         function insert( $table, $data, $format = null ) {
1258                 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1259         }
1260
1261         /**
1262          * Replace a row into a table.
1263          *
1264          * <code>
1265          * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1266          * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1267          * </code>
1268          *
1269          * @since 3.0.0
1270          * @see wpdb::prepare()
1271          * @see wpdb::$field_types
1272          * @see wp_set_wpdb_vars()
1273          *
1274          * @param string $table table name
1275          * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1276          * @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.
1277          *      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.
1278          * @return int|false The number of rows affected, or false on error.
1279          */
1280         function replace( $table, $data, $format = null ) {
1281                 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1282         }
1283
1284         /**
1285          * Helper function for insert and replace.
1286          *
1287          * Runs an insert or replace query based on $type argument.
1288          *
1289          * @access private
1290          * @since 3.0.0
1291          * @see wpdb::prepare()
1292          * @see wpdb::$field_types
1293          * @see wp_set_wpdb_vars()
1294          *
1295          * @param string $table table name
1296          * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1297          * @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.
1298          *      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.
1299          * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1300          * @return int|false The number of rows affected, or false on error.
1301          */
1302         function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1303                 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
1304                         return false;
1305                 $this->insert_id = 0;
1306                 $formats = $format = (array) $format;
1307                 $fields = array_keys( $data );
1308                 $formatted_fields = array();
1309                 foreach ( $fields as $field ) {
1310                         if ( !empty( $format ) )
1311                                 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1312                         elseif ( isset( $this->field_types[$field] ) )
1313                                 $form = $this->field_types[$field];
1314                         else
1315                                 $form = '%s';
1316                         $formatted_fields[] = $form;
1317                 }
1318                 $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
1319                 return $this->query( $this->prepare( $sql, $data ) );
1320         }
1321
1322         /**
1323          * Update a row in the table
1324          *
1325          * <code>
1326          * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1327          * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1328          * </code>
1329          *
1330          * @since 2.5.0
1331          * @see wpdb::prepare()
1332          * @see wpdb::$field_types
1333          * @see wp_set_wpdb_vars()
1334          *
1335          * @param string $table table name
1336          * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1337          * @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".
1338          * @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.
1339          *      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.
1340          * @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.
1341          * @return int|false The number of rows updated, or false on error.
1342          */
1343         function update( $table, $data, $where, $format = null, $where_format = null ) {
1344                 if ( ! is_array( $data ) || ! is_array( $where ) )
1345                         return false;
1346
1347                 $formats = $format = (array) $format;
1348                 $bits = $wheres = array();
1349                 foreach ( (array) array_keys( $data ) as $field ) {
1350                         if ( !empty( $format ) )
1351                                 $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
1352                         elseif ( isset($this->field_types[$field]) )
1353                                 $form = $this->field_types[$field];
1354                         else
1355                                 $form = '%s';
1356                         $bits[] = "`$field` = {$form}";
1357                 }
1358
1359                 $where_formats = $where_format = (array) $where_format;
1360                 foreach ( (array) array_keys( $where ) as $field ) {
1361                         if ( !empty( $where_format ) )
1362                                 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1363                         elseif ( isset( $this->field_types[$field] ) )
1364                                 $form = $this->field_types[$field];
1365                         else
1366                                 $form = '%s';
1367                         $wheres[] = "`$field` = {$form}";
1368                 }
1369
1370                 $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
1371                 return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
1372         }
1373
1374         /**
1375          * Delete a row in the table
1376          *
1377          * <code>
1378          * wpdb::delete( 'table', array( 'ID' => 1 ) )
1379          * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
1380          * </code>
1381          *
1382          * @since 3.4.0
1383          * @see wpdb::prepare()
1384          * @see wpdb::$field_types
1385          * @see wp_set_wpdb_vars()
1386          *
1387          * @param string $table table name
1388          * @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".
1389          * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
1390          * @return int|false The number of rows updated, or false on error.
1391          */
1392         function delete( $table, $where, $where_format = null ) {
1393                 if ( ! is_array( $where ) )
1394                         return false;
1395
1396                 $bits = $wheres = array();
1397
1398                 $where_formats = $where_format = (array) $where_format;
1399
1400                 foreach ( array_keys( $where ) as $field ) {
1401                         if ( !empty( $where_format ) ) {
1402                                 $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
1403                         } elseif ( isset( $this->field_types[ $field ] ) ) {
1404                                 $form = $this->field_types[ $field ];
1405                         } else {
1406                                 $form = '%s';
1407                         }
1408
1409                         $wheres[] = "$field = $form";
1410                 }
1411
1412                 $sql = "DELETE FROM $table WHERE " . implode( ' AND ', $wheres );
1413                 return $this->query( $this->prepare( $sql, $where ) );
1414         }
1415
1416
1417         /**
1418          * Retrieve one variable from the database.
1419          *
1420          * Executes a SQL query and returns the value from the SQL result.
1421          * 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.
1422          * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
1423          *
1424          * @since 0.71
1425          *
1426          * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
1427          * @param int $x Optional. Column of value to return. Indexed from 0.
1428          * @param int $y Optional. Row of value to return. Indexed from 0.
1429          * @return string|null Database query result (as string), or null on failure
1430          */
1431         function get_var( $query = null, $x = 0, $y = 0 ) {
1432                 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
1433                 if ( $query )
1434                         $this->query( $query );
1435
1436                 // Extract var out of cached results based x,y vals
1437                 if ( !empty( $this->last_result[$y] ) ) {
1438                         $values = array_values( get_object_vars( $this->last_result[$y] ) );
1439                 }
1440
1441                 // If there is a value return it else return null
1442                 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
1443         }
1444
1445         /**
1446          * Retrieve one row from the database.
1447          *
1448          * Executes a SQL query and returns the row from the SQL result.
1449          *
1450          * @since 0.71
1451          *
1452          * @param string|null $query SQL query.
1453          * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
1454          *      a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
1455          * @param int $y Optional. Row to return. Indexed from 0.
1456          * @return mixed Database query result in format specified by $output or null on failure
1457          */
1458         function get_row( $query = null, $output = OBJECT, $y = 0 ) {
1459                 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
1460                 if ( $query )
1461                         $this->query( $query );
1462                 else
1463                         return null;
1464
1465                 if ( !isset( $this->last_result[$y] ) )
1466                         return null;
1467
1468                 if ( $output == OBJECT ) {
1469                         return $this->last_result[$y] ? $this->last_result[$y] : null;
1470                 } elseif ( $output == ARRAY_A ) {
1471                         return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
1472                 } elseif ( $output == ARRAY_N ) {
1473                         return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
1474                 } else {
1475                         $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
1476                 }
1477         }
1478
1479         /**
1480          * Retrieve one column from the database.
1481          *
1482          * Executes a SQL query and returns the column from the SQL result.
1483          * If the SQL result contains more than one column, this function returns the column specified.
1484          * If $query is null, this function returns the specified column from the previous SQL result.
1485          *
1486          * @since 0.71
1487          *
1488          * @param string|null $query Optional. SQL query. Defaults to previous query.
1489          * @param int $x Optional. Column to return. Indexed from 0.
1490          * @return array Database query result. Array indexed from 0 by SQL result row number.
1491          */
1492         function get_col( $query = null , $x = 0 ) {
1493                 if ( $query )
1494                         $this->query( $query );
1495
1496                 $new_array = array();
1497                 // Extract the column values
1498                 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
1499                         $new_array[$i] = $this->get_var( null, $x, $i );
1500                 }
1501                 return $new_array;
1502         }
1503
1504         /**
1505          * Retrieve an entire SQL result set from the database (i.e., many rows)
1506          *
1507          * Executes a SQL query and returns the entire SQL result.
1508          *
1509          * @since 0.71
1510          *
1511          * @param string $query SQL query.
1512          * @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.
1513          *      Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
1514          *      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.
1515          * @return mixed Database query results
1516          */
1517         function get_results( $query = null, $output = OBJECT ) {
1518                 $this->func_call = "\$db->get_results(\"$query\", $output)";
1519
1520                 if ( $query )
1521                         $this->query( $query );
1522                 else
1523                         return null;
1524
1525                 $new_array = array();
1526                 if ( $output == OBJECT ) {
1527                         // Return an integer-keyed array of row objects
1528                         return $this->last_result;
1529                 } elseif ( $output == OBJECT_K ) {
1530                         // Return an array of row objects with keys from column 1
1531                         // (Duplicates are discarded)
1532                         foreach ( $this->last_result as $row ) {
1533                                 $var_by_ref = get_object_vars( $row );
1534                                 $key = array_shift( $var_by_ref );
1535                                 if ( ! isset( $new_array[ $key ] ) )
1536                                         $new_array[ $key ] = $row;
1537                         }
1538                         return $new_array;
1539                 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1540                         // Return an integer-keyed array of...
1541                         if ( $this->last_result ) {
1542                                 foreach( (array) $this->last_result as $row ) {
1543                                         if ( $output == ARRAY_N ) {
1544                                                 // ...integer-keyed row arrays
1545                                                 $new_array[] = array_values( get_object_vars( $row ) );
1546                                         } else {
1547                                                 // ...column name-keyed row arrays
1548                                                 $new_array[] = get_object_vars( $row );
1549                                         }
1550                                 }
1551                         }
1552                         return $new_array;
1553                 }
1554                 return null;
1555         }
1556
1557         /**
1558          * Load the column metadata from the last query.
1559          *
1560          * @since 3.5.0
1561          *
1562          * @access protected
1563          */
1564         protected function load_col_info() {
1565                 if ( $this->col_info )
1566                         return;
1567
1568                 for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
1569                         $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
1570                 }
1571         }
1572
1573         /**
1574          * Retrieve column metadata from the last query.
1575          *
1576          * @since 0.71
1577          *
1578          * @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
1579          * @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
1580          * @return mixed Column Results
1581          */
1582         function get_col_info( $info_type = 'name', $col_offset = -1 ) {
1583                 $this->load_col_info();
1584
1585                 if ( $this->col_info ) {
1586                         if ( $col_offset == -1 ) {
1587                                 $i = 0;
1588                                 $new_array = array();
1589                                 foreach( (array) $this->col_info as $col ) {
1590                                         $new_array[$i] = $col->{$info_type};
1591                                         $i++;
1592                                 }
1593                                 return $new_array;
1594                         } else {
1595                                 return $this->col_info[$col_offset]->{$info_type};
1596                         }
1597                 }
1598         }
1599
1600         /**
1601          * Starts the timer, for debugging purposes.
1602          *
1603          * @since 1.5.0
1604          *
1605          * @return true
1606          */
1607         function timer_start() {
1608                 $this->time_start = microtime( true );
1609                 return true;
1610         }
1611
1612         /**
1613          * Stops the debugging timer.
1614          *
1615          * @since 1.5.0
1616          *
1617          * @return float Total time spent on the query, in seconds
1618          */
1619         function timer_stop() {
1620                 return ( microtime( true ) - $this->time_start );
1621         }
1622
1623         /**
1624          * Wraps errors in a nice header and footer and dies.
1625          *
1626          * Will not die if wpdb::$show_errors is false.
1627          *
1628          * @since 1.5.0
1629          *
1630          * @param string $message The Error message
1631          * @param string $error_code Optional. A Computer readable string to identify the error.
1632          * @return false|void
1633          */
1634         function bail( $message, $error_code = '500' ) {
1635                 if ( !$this->show_errors ) {
1636                         if ( class_exists( 'WP_Error' ) )
1637                                 $this->error = new WP_Error($error_code, $message);
1638                         else
1639                                 $this->error = $message;
1640                         return false;
1641                 }
1642                 wp_die($message);
1643         }
1644
1645         /**
1646          * Whether MySQL database is at least the required minimum version.
1647          *
1648          * @since 2.5.0
1649          * @uses $wp_version
1650          * @uses $required_mysql_version
1651          *
1652          * @return WP_Error
1653          */
1654         function check_database_version() {
1655                 global $wp_version, $required_mysql_version;
1656                 // Make sure the server has the required MySQL version
1657                 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
1658                         return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
1659         }
1660
1661         /**
1662          * Whether the database supports collation.
1663          *
1664          * Called when WordPress is generating the table scheme.
1665          *
1666          * @since 2.5.0
1667          * @deprecated 3.5.0
1668          * @deprecated Use wpdb::has_cap( 'collation' )
1669          *
1670          * @return bool True if collation is supported, false if version does not
1671          */
1672         function supports_collation() {
1673                 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
1674                 return $this->has_cap( 'collation' );
1675         }
1676
1677         /**
1678          * The database character collate.
1679          *
1680          * @since 3.5.0
1681          *
1682          * @return string The database character collate.
1683          */
1684         public function get_charset_collate() {
1685                 $charset_collate = '';
1686
1687                 if ( ! empty( $this->charset ) )
1688                         $charset_collate = "DEFAULT CHARACTER SET $this->charset";
1689                 if ( ! empty( $this->collate ) )
1690                         $charset_collate .= " COLLATE $this->collate";
1691
1692                 return $charset_collate;
1693         }
1694
1695         /**
1696          * Determine if a database supports a particular feature
1697          *
1698          * @since 2.7.0
1699          * @see   wpdb::db_version()
1700          *
1701          * @param string $db_cap the feature
1702          * @return bool
1703          */
1704         function has_cap( $db_cap ) {
1705                 $version = $this->db_version();
1706
1707                 switch ( strtolower( $db_cap ) ) {
1708                         case 'collation' :    // @since 2.5.0
1709                         case 'group_concat' : // @since 2.7
1710                         case 'subqueries' :   // @since 2.7
1711                                 return version_compare( $version, '4.1', '>=' );
1712                         case 'set_charset' :
1713                                 return version_compare($version, '5.0.7', '>=');
1714                 };
1715
1716                 return false;
1717         }
1718
1719         /**
1720          * Retrieve the name of the function that called wpdb.
1721          *
1722          * Searches up the list of functions until it reaches
1723          * the one that would most logically had called this method.
1724          *
1725          * @since 2.5.0
1726          *
1727          * @return string The name of the calling function
1728          */
1729         function get_caller() {
1730                 return wp_debug_backtrace_summary( __CLASS__ );
1731         }
1732
1733         /**
1734          * The database version number.
1735          *
1736          * @since 2.7.0
1737          *
1738          * @return false|string false on failure, version number on success
1739          */
1740         function db_version() {
1741                 return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );
1742         }
1743 }