PageRenderTime 64ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/wp-db.php

https://bitbucket.org/broderboy/shannonbroder-wordpress
PHP | 2150 lines | 856 code | 220 blank | 1074 comment | 214 complexity | a64d49551cc4ca7aa9575dbd6625e16a MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file