PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/wp-db.php

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

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