PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/wp-db.php

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