PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/wp-db.php

https://github.com/jao/jpcamargo
PHP | 1143 lines | 441 code | 123 blank | 579 comment | 88 complexity | 652daa9f48e829ee856367763488fc12 MD5 | raw 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', true);
  19. /**
  20. * @since {@internal Version Unknown}}
  21. */
  22. define('OBJECT_K', 'OBJECT_K', false);
  23. /**
  24. * @since 0.71
  25. */
  26. define('ARRAY_A', 'ARRAY_A', false);
  27. /**
  28. * @since 0.71
  29. */
  30. define('ARRAY_N', 'ARRAY_N', false);
  31. /**
  32. * WordPress Database Access Abstraction Object
  33. *
  34. * It is possible to replace this class with your own
  35. * by setting the $wpdb global variable in wp-content/db.php
  36. * file with your class. You can name it wpdb also, since
  37. * this file will not be included, if the other file is
  38. * available.
  39. *
  40. * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
  41. *
  42. * @package WordPress
  43. * @subpackage Database
  44. * @since 0.71
  45. * @final
  46. */
  47. class wpdb {
  48. /**
  49. * Whether to show SQL/DB errors
  50. *
  51. * @since 0.71
  52. * @access private
  53. * @var bool
  54. */
  55. var $show_errors = false;
  56. /**
  57. * Whether to suppress errors during the DB bootstrapping.
  58. *
  59. * @access private
  60. * @since {@internal Version Unknown}}
  61. * @var bool
  62. */
  63. var $suppress_errors = false;
  64. /**
  65. * The last error during query.
  66. *
  67. * @since {@internal Version Unknown}}
  68. * @var string
  69. */
  70. var $last_error = '';
  71. /**
  72. * Amount of queries made
  73. *
  74. * @since 1.2.0
  75. * @access private
  76. * @var int
  77. */
  78. var $num_queries = 0;
  79. /**
  80. * Saved result of the last query made
  81. *
  82. * @since 1.2.0
  83. * @access private
  84. * @var array
  85. */
  86. var $last_query;
  87. /**
  88. * Saved info on the table column
  89. *
  90. * @since 1.2.0
  91. * @access private
  92. * @var array
  93. */
  94. var $col_info;
  95. /**
  96. * Saved queries that were executed
  97. *
  98. * @since 1.5.0
  99. * @access private
  100. * @var array
  101. */
  102. var $queries;
  103. /**
  104. * WordPress table prefix
  105. *
  106. * You can set this to have multiple WordPress installations
  107. * in a single database. The second reason is for possible
  108. * security precautions.
  109. *
  110. * @since 0.71
  111. * @access private
  112. * @var string
  113. */
  114. var $prefix = '';
  115. /**
  116. * Whether the database queries are ready to start executing.
  117. *
  118. * @since 2.5.0
  119. * @access private
  120. * @var bool
  121. */
  122. var $ready = false;
  123. /**
  124. * WordPress Posts table
  125. *
  126. * @since 1.5.0
  127. * @access public
  128. * @var string
  129. */
  130. var $posts;
  131. /**
  132. * WordPress Users table
  133. *
  134. * @since 1.5.0
  135. * @access public
  136. * @var string
  137. */
  138. var $users;
  139. /**
  140. * WordPress Categories table
  141. *
  142. * @since 1.5.0
  143. * @access public
  144. * @var string
  145. */
  146. var $categories;
  147. /**
  148. * WordPress Post to Category table
  149. *
  150. * @since 1.5.0
  151. * @access public
  152. * @var string
  153. */
  154. var $post2cat;
  155. /**
  156. * WordPress Comments table
  157. *
  158. * @since 1.5.0
  159. * @access public
  160. * @var string
  161. */
  162. var $comments;
  163. /**
  164. * WordPress Links table
  165. *
  166. * @since 1.5.0
  167. * @access public
  168. * @var string
  169. */
  170. var $links;
  171. /**
  172. * WordPress Options table
  173. *
  174. * @since 1.5.0
  175. * @access public
  176. * @var string
  177. */
  178. var $options;
  179. /**
  180. * WordPress Post Metadata table
  181. *
  182. * @since {@internal Version Unknown}}
  183. * @access public
  184. * @var string
  185. */
  186. var $postmeta;
  187. /**
  188. * WordPress Comment Metadata table
  189. *
  190. * @since 2.9
  191. * @access public
  192. * @var string
  193. */
  194. var $commentmeta;
  195. /**
  196. * WordPress User Metadata table
  197. *
  198. * @since 2.3.0
  199. * @access public
  200. * @var string
  201. */
  202. var $usermeta;
  203. /**
  204. * WordPress Terms table
  205. *
  206. * @since 2.3.0
  207. * @access public
  208. * @var string
  209. */
  210. var $terms;
  211. /**
  212. * WordPress Term Taxonomy table
  213. *
  214. * @since 2.3.0
  215. * @access public
  216. * @var string
  217. */
  218. var $term_taxonomy;
  219. /**
  220. * WordPress Term Relationships table
  221. *
  222. * @since 2.3.0
  223. * @access public
  224. * @var string
  225. */
  226. var $term_relationships;
  227. /**
  228. * List of WordPress tables
  229. *
  230. * @since {@internal Version Unknown}}
  231. * @access private
  232. * @var array
  233. */
  234. var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  235. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta');
  236. /**
  237. * List of deprecated WordPress tables
  238. *
  239. * @since 2.9.0
  240. * @access private
  241. * @var array
  242. */
  243. var $old_tables = array('categories', 'post2cat', 'link2cat');
  244. /**
  245. * Format specifiers for DB columns. Columns not listed here default to %s. Initialized in wp-settings.php.
  246. *
  247. * Keys are colmn names, values are format types: 'ID' => '%d'
  248. *
  249. * @since 2.8.0
  250. * @see wpdb:prepare()
  251. * @see wpdb:insert()
  252. * @see wpdb:update()
  253. * @access public
  254. * @war array
  255. */
  256. var $field_types = array();
  257. /**
  258. * Database table columns charset
  259. *
  260. * @since 2.2.0
  261. * @access public
  262. * @var string
  263. */
  264. var $charset;
  265. /**
  266. * Database table columns collate
  267. *
  268. * @since 2.2.0
  269. * @access public
  270. * @var string
  271. */
  272. var $collate;
  273. /**
  274. * Whether to use mysql_real_escape_string
  275. *
  276. * @since 2.8.0
  277. * @access public
  278. * @var bool
  279. */
  280. var $real_escape = false;
  281. /**
  282. * Database Username
  283. *
  284. * @since 2.9.0
  285. * @access private
  286. * @var string
  287. */
  288. var $dbuser;
  289. /**
  290. * Connects to the database server and selects a database
  291. *
  292. * PHP4 compatibility layer for calling the PHP5 constructor.
  293. *
  294. * @uses wpdb::__construct() Passes parameters and returns result
  295. * @since 0.71
  296. *
  297. * @param string $dbuser MySQL database user
  298. * @param string $dbpassword MySQL database password
  299. * @param string $dbname MySQL database name
  300. * @param string $dbhost MySQL database host
  301. */
  302. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  303. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  304. }
  305. /**
  306. * Connects to the database server and selects a database
  307. *
  308. * PHP5 style constructor for compatibility with PHP5. Does
  309. * the actual setting up of the class properties and connection
  310. * to the database.
  311. *
  312. * @since 2.0.8
  313. *
  314. * @param string $dbuser MySQL database user
  315. * @param string $dbpassword MySQL database password
  316. * @param string $dbname MySQL database name
  317. * @param string $dbhost MySQL database host
  318. */
  319. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  320. register_shutdown_function(array(&$this, "__destruct"));
  321. if ( defined('WP_DEBUG') and WP_DEBUG == true )
  322. $this->show_errors();
  323. if ( defined('DB_CHARSET') )
  324. $this->charset = DB_CHARSET;
  325. if ( defined('DB_COLLATE') )
  326. $this->collate = DB_COLLATE;
  327. $this->dbuser = $dbuser;
  328. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
  329. if (!$this->dbh) {
  330. $this->bail(sprintf(/*WP_I18N_DB_CONN_ERROR*/"
  331. <h1>Error establishing a database connection</h1>
  332. <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>
  333. <ul>
  334. <li>Are you sure you have the correct username and password?</li>
  335. <li>Are you sure that you have typed the correct hostname?</li>
  336. <li>Are you sure that the database server is running?</li>
  337. </ul>
  338. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  339. "/*/WP_I18N_DB_CONN_ERROR*/, $dbhost), 'db_connect_fail');
  340. return;
  341. }
  342. $this->ready = true;
  343. if ( $this->has_cap( 'collation' ) ) {
  344. if ( !empty($this->charset) ) {
  345. if ( function_exists('mysql_set_charset') ) {
  346. mysql_set_charset($this->charset, $this->dbh);
  347. $this->real_escape = true;
  348. } else {
  349. $collation_query = "SET NAMES '{$this->charset}'";
  350. if ( !empty($this->collate) )
  351. $collation_query .= " COLLATE '{$this->collate}'";
  352. $this->query($collation_query);
  353. }
  354. }
  355. }
  356. $this->select($dbname);
  357. }
  358. /**
  359. * PHP5 style destructor and will run when database object is destroyed.
  360. *
  361. * @since 2.0.8
  362. *
  363. * @return bool Always true
  364. */
  365. function __destruct() {
  366. return true;
  367. }
  368. /**
  369. * Sets the table prefix for the WordPress tables.
  370. *
  371. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  372. * override the WordPress users and usersmeta tables that would otherwise be determined by the $prefix.
  373. *
  374. * @since 2.5.0
  375. *
  376. * @param string $prefix Alphanumeric name for the new prefix.
  377. * @return string|WP_Error Old prefix or WP_Error on error
  378. */
  379. function set_prefix($prefix) {
  380. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  381. return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
  382. $old_prefix = $this->prefix;
  383. $this->prefix = $prefix;
  384. foreach ( (array) $this->tables as $table )
  385. $this->$table = $this->prefix . $table;
  386. if ( defined('CUSTOM_USER_TABLE') )
  387. $this->users = CUSTOM_USER_TABLE;
  388. if ( defined('CUSTOM_USER_META_TABLE') )
  389. $this->usermeta = CUSTOM_USER_META_TABLE;
  390. return $old_prefix;
  391. }
  392. /**
  393. * Selects a database using the current database connection.
  394. *
  395. * The database name will be changed based on the current database
  396. * connection. On failure, the execution will bail and display an DB error.
  397. *
  398. * @since 0.71
  399. *
  400. * @param string $db MySQL database name
  401. * @return null Always null.
  402. */
  403. function select($db) {
  404. if (!@mysql_select_db($db, $this->dbh)) {
  405. $this->ready = false;
  406. $this->bail(sprintf(/*WP_I18N_DB_SELECT_DB*/'
  407. <h1>Can&#8217;t select database</h1>
  408. <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>
  409. <ul>
  410. <li>Are you sure it exists?</li>
  411. <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
  412. <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>
  413. </ul>
  414. <p>If you don\'t know how to setup a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="http://wordpress.org/support/">WordPress Support Forums</a>.</p>'/*/WP_I18N_DB_SELECT_DB*/, $db, $this->dbuser), 'db_select_fail');
  415. return;
  416. }
  417. }
  418. function _weak_escape($string) {
  419. return addslashes($string);
  420. }
  421. function _real_escape($string) {
  422. if ( $this->dbh && $this->real_escape )
  423. return mysql_real_escape_string( $string, $this->dbh );
  424. else
  425. return addslashes( $string );
  426. }
  427. function _escape($data) {
  428. if ( is_array($data) ) {
  429. foreach ( (array) $data as $k => $v ) {
  430. if ( is_array($v) )
  431. $data[$k] = $this->_escape( $v );
  432. else
  433. $data[$k] = $this->_real_escape( $v );
  434. }
  435. } else {
  436. $data = $this->_real_escape( $data );
  437. }
  438. return $data;
  439. }
  440. /**
  441. * Escapes content for insertion into the database using addslashes(), for security
  442. *
  443. * @since 0.71
  444. *
  445. * @param string|array $data
  446. * @return string query safe string
  447. */
  448. function escape($data) {
  449. if ( is_array($data) ) {
  450. foreach ( (array) $data as $k => $v ) {
  451. if ( is_array($v) )
  452. $data[$k] = $this->escape( $v );
  453. else
  454. $data[$k] = $this->_weak_escape( $v );
  455. }
  456. } else {
  457. $data = $this->_weak_escape( $data );
  458. }
  459. return $data;
  460. }
  461. /**
  462. * Escapes content by reference for insertion into the database, for security
  463. *
  464. * @since 2.3.0
  465. *
  466. * @param string $s
  467. */
  468. function escape_by_ref(&$string) {
  469. $string = $this->_real_escape( $string );
  470. }
  471. /**
  472. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  473. *
  474. * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
  475. * Does not support sign, padding, alignment, width or precision specifiers.
  476. * Does not support argument numbering/swapping.
  477. *
  478. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  479. *
  480. * Both %d and %s should be left unquoted in the query string.
  481. *
  482. * <code>
  483. * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", "foo", 1337 )
  484. * </code>
  485. *
  486. * @link http://php.net/sprintf Description of syntax.
  487. * @since 2.3.0
  488. *
  489. * @param string $query Query statement with sprintf()-like placeholders
  490. * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}.
  491. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}.
  492. * @return null|string Sanitized query string
  493. */
  494. function prepare($query = null) { // ( $query, *$args )
  495. if ( is_null( $query ) )
  496. return;
  497. $args = func_get_args();
  498. array_shift($args);
  499. // If args were passed as an array (as in vsprintf), move them up
  500. if ( isset($args[0]) && is_array($args[0]) )
  501. $args = $args[0];
  502. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  503. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  504. $query = str_replace('%s', "'%s'", $query); // quote the strings
  505. array_walk($args, array(&$this, 'escape_by_ref'));
  506. return @vsprintf($query, $args);
  507. }
  508. /**
  509. * Print SQL/DB error.
  510. *
  511. * @since 0.71
  512. * @global array $EZSQL_ERROR Stores error information of query and error string
  513. *
  514. * @param string $str The error to display
  515. * @return bool False if the showing of errors is disabled.
  516. */
  517. function print_error($str = '') {
  518. global $EZSQL_ERROR;
  519. if (!$str) $str = mysql_error($this->dbh);
  520. $EZSQL_ERROR[] = array ('query' => $this->last_query, 'error_str' => $str);
  521. if ( $this->suppress_errors )
  522. return false;
  523. if ( $caller = $this->get_caller() )
  524. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress database error %1$s for query %2$s made by %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller);
  525. else
  526. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR*/'WordPress database error %1$s for query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query);
  527. $log_error = true;
  528. if ( ! function_exists('error_log') )
  529. $log_error = false;
  530. $log_file = @ini_get('error_log');
  531. if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) )
  532. $log_error = false;
  533. if ( $log_error )
  534. @error_log($error_str, 0);
  535. // Is error output turned on or not..
  536. if ( !$this->show_errors )
  537. return false;
  538. $str = htmlspecialchars($str, ENT_QUOTES);
  539. $query = htmlspecialchars($this->last_query, ENT_QUOTES);
  540. // If there is an error then take note of it
  541. print "<div id='error'>
  542. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  543. <code>$query</code></p>
  544. </div>";
  545. }
  546. /**
  547. * Enables showing of database errors.
  548. *
  549. * This function should be used only to enable showing of errors.
  550. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  551. * this function can be used to enable and disable showing of database
  552. * errors.
  553. *
  554. * @since 0.71
  555. *
  556. * @param bool $show Whether to show or hide errors
  557. * @return bool Old value for showing errors.
  558. */
  559. function show_errors( $show = true ) {
  560. $errors = $this->show_errors;
  561. $this->show_errors = $show;
  562. return $errors;
  563. }
  564. /**
  565. * Disables showing of database errors.
  566. *
  567. * @since 0.71
  568. *
  569. * @return bool Whether showing of errors was active or not
  570. */
  571. function hide_errors() {
  572. $show = $this->show_errors;
  573. $this->show_errors = false;
  574. return $show;
  575. }
  576. /**
  577. * Whether to suppress database errors.
  578. *
  579. * @param unknown_type $suppress
  580. * @return unknown
  581. */
  582. function suppress_errors( $suppress = true ) {
  583. $errors = $this->suppress_errors;
  584. $this->suppress_errors = $suppress;
  585. return $errors;
  586. }
  587. /**
  588. * Kill cached query results.
  589. *
  590. * @since 0.71
  591. */
  592. function flush() {
  593. $this->last_result = array();
  594. $this->col_info = null;
  595. $this->last_query = null;
  596. }
  597. /**
  598. * Perform a MySQL database query, using current database connection.
  599. *
  600. * More information can be found on the codex page.
  601. *
  602. * @since 0.71
  603. *
  604. * @param string $query
  605. * @return int|false Number of rows affected/selected or false on error
  606. */
  607. function query($query) {
  608. if ( ! $this->ready )
  609. return false;
  610. // filter the query, if filters are available
  611. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  612. if ( function_exists('apply_filters') )
  613. $query = apply_filters('query', $query);
  614. // initialise return
  615. $return_val = 0;
  616. $this->flush();
  617. // Log how the function was called
  618. $this->func_call = "\$db->query(\"$query\")";
  619. // Keep track of the last query for debug..
  620. $this->last_query = $query;
  621. // Perform the query via std mysql_query function..
  622. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  623. $this->timer_start();
  624. $this->result = @mysql_query($query, $this->dbh);
  625. ++$this->num_queries;
  626. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  627. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  628. // If there is an error then take note of it..
  629. if ( $this->last_error = mysql_error($this->dbh) ) {
  630. $this->print_error();
  631. return false;
  632. }
  633. if ( preg_match("/^\\s*(insert|delete|update|replace|alter) /i",$query) ) {
  634. $this->rows_affected = mysql_affected_rows($this->dbh);
  635. // Take note of the insert_id
  636. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  637. $this->insert_id = mysql_insert_id($this->dbh);
  638. }
  639. // Return number of rows affected
  640. $return_val = $this->rows_affected;
  641. } else {
  642. $i = 0;
  643. while ($i < @mysql_num_fields($this->result)) {
  644. $this->col_info[$i] = @mysql_fetch_field($this->result);
  645. $i++;
  646. }
  647. $num_rows = 0;
  648. while ( $row = @mysql_fetch_object($this->result) ) {
  649. $this->last_result[$num_rows] = $row;
  650. $num_rows++;
  651. }
  652. @mysql_free_result($this->result);
  653. // Log number of rows the query returned
  654. $this->num_rows = $num_rows;
  655. // Return number of rows selected
  656. $return_val = $this->num_rows;
  657. }
  658. return $return_val;
  659. }
  660. /**
  661. * Insert a row into a table.
  662. *
  663. * <code>
  664. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  665. * </code>
  666. *
  667. * @since 2.5.0
  668. * @see wpdb::prepare()
  669. *
  670. * @param string $table table name
  671. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  672. * @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. A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings.
  673. * @return int|false The number of rows inserted, or false on error.
  674. */
  675. function insert($table, $data, $format = null) {
  676. $formats = $format = (array) $format;
  677. $fields = array_keys($data);
  678. $formatted_fields = array();
  679. foreach ( $fields as $field ) {
  680. if ( !empty($format) )
  681. $form = ( $form = array_shift($formats) ) ? $form : $format[0];
  682. elseif ( isset($this->field_types[$field]) )
  683. $form = $this->field_types[$field];
  684. else
  685. $form = '%s';
  686. $formatted_fields[] = $form;
  687. }
  688. $sql = "INSERT INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
  689. return $this->query( $this->prepare( $sql, $data) );
  690. }
  691. /**
  692. * Update a row in the table
  693. *
  694. * <code>
  695. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  696. * </code>
  697. *
  698. * @since 2.5.0
  699. * @see wpdb::prepare()
  700. *
  701. * @param string $table table name
  702. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  703. * @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".
  704. * @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. A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings.
  705. * @param array|string $format_where (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', '%s' (decimal number, string). If omitted, all values in $where will be treated as strings.
  706. * @return int|false The number of rows updated, or false on error.
  707. */
  708. function update($table, $data, $where, $format = null, $where_format = null) {
  709. if ( !is_array( $where ) )
  710. return false;
  711. $formats = $format = (array) $format;
  712. $bits = $wheres = array();
  713. foreach ( (array) array_keys($data) as $field ) {
  714. if ( !empty($format) )
  715. $form = ( $form = array_shift($formats) ) ? $form : $format[0];
  716. elseif ( isset($this->field_types[$field]) )
  717. $form = $this->field_types[$field];
  718. else
  719. $form = '%s';
  720. $bits[] = "`$field` = {$form}";
  721. }
  722. $where_formats = $where_format = (array) $where_format;
  723. foreach ( (array) array_keys($where) as $field ) {
  724. if ( !empty($where_format) )
  725. $form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0];
  726. elseif ( isset($this->field_types[$field]) )
  727. $form = $this->field_types[$field];
  728. else
  729. $form = '%s';
  730. $wheres[] = "`$field` = {$form}";
  731. }
  732. $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
  733. return $this->query( $this->prepare( $sql, array_merge(array_values($data), array_values($where))) );
  734. }
  735. /**
  736. * Retrieve one variable from the database.
  737. *
  738. * Executes a SQL query and returns the value from the SQL result.
  739. * 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.
  740. * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
  741. *
  742. * @since 0.71
  743. *
  744. * @param string|null $query SQL query. If null, use the result from the previous query.
  745. * @param int $x (optional) Column of value to return. Indexed from 0.
  746. * @param int $y (optional) Row of value to return. Indexed from 0.
  747. * @return string Database query result
  748. */
  749. function get_var($query=null, $x = 0, $y = 0) {
  750. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  751. if ( $query )
  752. $this->query($query);
  753. // Extract var out of cached results based x,y vals
  754. if ( !empty( $this->last_result[$y] ) ) {
  755. $values = array_values(get_object_vars($this->last_result[$y]));
  756. }
  757. // If there is a value return it else return null
  758. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  759. }
  760. /**
  761. * Retrieve one row from the database.
  762. *
  763. * Executes a SQL query and returns the row from the SQL result.
  764. *
  765. * @since 0.71
  766. *
  767. * @param string|null $query SQL query.
  768. * @param string $output (optional) one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...), a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
  769. * @param int $y (optional) Row to return. Indexed from 0.
  770. * @return mixed Database query result in format specifed by $output
  771. */
  772. function get_row($query = null, $output = OBJECT, $y = 0) {
  773. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  774. if ( $query )
  775. $this->query($query);
  776. else
  777. return null;
  778. if ( !isset($this->last_result[$y]) )
  779. return null;
  780. if ( $output == OBJECT ) {
  781. return $this->last_result[$y] ? $this->last_result[$y] : null;
  782. } elseif ( $output == ARRAY_A ) {
  783. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  784. } elseif ( $output == ARRAY_N ) {
  785. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  786. } else {
  787. $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/WP_I18N_DB_GETROW_ERROR*/);
  788. }
  789. }
  790. /**
  791. * Retrieve one column from the database.
  792. *
  793. * Executes a SQL query and returns the column from the SQL result.
  794. * If the SQL result contains more than one column, this function returns the column specified.
  795. * If $query is null, this function returns the specified column from the previous SQL result.
  796. *
  797. * @since 0.71
  798. *
  799. * @param string|null $query SQL query. If null, use the result from the previous query.
  800. * @param int $x Column to return. Indexed from 0.
  801. * @return array Database query result. Array indexed from 0 by SQL result row number.
  802. */
  803. function get_col($query = null , $x = 0) {
  804. if ( $query )
  805. $this->query($query);
  806. $new_array = array();
  807. // Extract the column values
  808. for ( $i=0; $i < count($this->last_result); $i++ ) {
  809. $new_array[$i] = $this->get_var(null, $x, $i);
  810. }
  811. return $new_array;
  812. }
  813. /**
  814. * Retrieve an entire SQL result set from the database (i.e., many rows)
  815. *
  816. * Executes a SQL query and returns the entire SQL result.
  817. *
  818. * @since 0.71
  819. *
  820. * @param string $query SQL query.
  821. * @param string $output (optional) ane of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively. With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded.
  822. * @return mixed Database query results
  823. */
  824. function get_results($query = null, $output = OBJECT) {
  825. $this->func_call = "\$db->get_results(\"$query\", $output)";
  826. if ( $query )
  827. $this->query($query);
  828. else
  829. return null;
  830. if ( $output == OBJECT ) {
  831. // Return an integer-keyed array of row objects
  832. return $this->last_result;
  833. } elseif ( $output == OBJECT_K ) {
  834. // Return an array of row objects with keys from column 1
  835. // (Duplicates are discarded)
  836. foreach ( $this->last_result as $row ) {
  837. $key = array_shift( get_object_vars( $row ) );
  838. if ( !isset( $new_array[ $key ] ) )
  839. $new_array[ $key ] = $row;
  840. }
  841. return $new_array;
  842. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  843. // Return an integer-keyed array of...
  844. if ( $this->last_result ) {
  845. $i = 0;
  846. foreach( (array) $this->last_result as $row ) {
  847. if ( $output == ARRAY_N ) {
  848. // ...integer-keyed row arrays
  849. $new_array[$i] = array_values( get_object_vars( $row ) );
  850. } else {
  851. // ...column name-keyed row arrays
  852. $new_array[$i] = get_object_vars( $row );
  853. }
  854. ++$i;
  855. }
  856. return $new_array;
  857. }
  858. }
  859. }
  860. /**
  861. * Retrieve column metadata from the last query.
  862. *
  863. * @since 0.71
  864. *
  865. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  866. * @param int $col_offset 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
  867. * @return mixed Column Results
  868. */
  869. function get_col_info($info_type = 'name', $col_offset = -1) {
  870. if ( $this->col_info ) {
  871. if ( $col_offset == -1 ) {
  872. $i = 0;
  873. foreach( (array) $this->col_info as $col ) {
  874. $new_array[$i] = $col->{$info_type};
  875. $i++;
  876. }
  877. return $new_array;
  878. } else {
  879. return $this->col_info[$col_offset]->{$info_type};
  880. }
  881. }
  882. }
  883. /**
  884. * Starts the timer, for debugging purposes.
  885. *
  886. * @since 1.5.0
  887. *
  888. * @return true
  889. */
  890. function timer_start() {
  891. $mtime = microtime();
  892. $mtime = explode(' ', $mtime);
  893. $this->time_start = $mtime[1] + $mtime[0];
  894. return true;
  895. }
  896. /**
  897. * Stops the debugging timer.
  898. *
  899. * @since 1.5.0
  900. *
  901. * @return int Total time spent on the query, in milliseconds
  902. */
  903. function timer_stop() {
  904. $mtime = microtime();
  905. $mtime = explode(' ', $mtime);
  906. $time_end = $mtime[1] + $mtime[0];
  907. $time_total = $time_end - $this->time_start;
  908. return $time_total;
  909. }
  910. /**
  911. * Wraps errors in a nice header and footer and dies.
  912. *
  913. * Will not die if wpdb::$show_errors is true
  914. *
  915. * @since 1.5.0
  916. *
  917. * @param string $message The Error message
  918. * @param string $error_code (optional) A Computer readable string to identify the error.
  919. * @return false|void
  920. */
  921. function bail($message, $error_code = '500') {
  922. if ( !$this->show_errors ) {
  923. if ( class_exists('WP_Error') )
  924. $this->error = new WP_Error($error_code, $message);
  925. else
  926. $this->error = $message;
  927. return false;
  928. }
  929. wp_die($message);
  930. }
  931. /**
  932. * Whether or not MySQL database is at least the required minimum version.
  933. *
  934. * @since 2.5.0
  935. * @uses $wp_version
  936. *
  937. * @return WP_Error
  938. */
  939. function check_database_version()
  940. {
  941. global $wp_version;
  942. // Make sure the server has MySQL 4.0
  943. if ( version_compare($this->db_version(), '4.0.0', '<') )
  944. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
  945. }
  946. /**
  947. * Whether of not the database supports collation.
  948. *
  949. * Called when WordPress is generating the table scheme.
  950. *
  951. * @since 2.5.0
  952. *
  953. * @return bool True if collation is supported, false if version does not
  954. */
  955. function supports_collation() {
  956. return $this->has_cap( 'collation' );
  957. }
  958. /**
  959. * Generic function to determine if a database supports a particular feature
  960. * @param string $db_cap the feature
  961. * @param false|string|resource $dbh_or_table (not implemented) Which database to test. False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource.
  962. * @return bool
  963. */
  964. function has_cap( $db_cap ) {
  965. $version = $this->db_version();
  966. switch ( strtolower( $db_cap ) ) :
  967. case 'collation' : // @since 2.5.0
  968. case 'group_concat' : // @since 2.7
  969. case 'subqueries' : // @since 2.7
  970. return version_compare($version, '4.1', '>=');
  971. break;
  972. endswitch;
  973. return false;
  974. }
  975. /**
  976. * Retrieve the name of the function that called wpdb.
  977. *
  978. * Requires PHP 4.3 and searches up the list of functions until it reaches
  979. * the one that would most logically had called this method.
  980. *
  981. * @since 2.5.0
  982. *
  983. * @return string The name of the calling function
  984. */
  985. function get_caller() {
  986. // requires PHP 4.3+
  987. if ( !is_callable('debug_backtrace') )
  988. return '';
  989. $bt = debug_backtrace();
  990. $caller = array();
  991. $bt = array_reverse( $bt );
  992. foreach ( (array) $bt as $call ) {
  993. if ( @$call['class'] == __CLASS__ )
  994. continue;
  995. $function = $call['function'];
  996. if ( isset( $call['class'] ) )
  997. $function = $call['class'] . "->$function";
  998. $caller[] = $function;
  999. }
  1000. $caller = join( ', ', $caller );
  1001. return $caller;
  1002. }
  1003. /**
  1004. * The database version number
  1005. * @param false|string|resource $dbh_or_table (not implemented) Which database to test. False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource.
  1006. * @return false|string false on failure, version number on success
  1007. */
  1008. function db_version() {
  1009. return preg_replace('/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ));
  1010. }
  1011. }
  1012. if ( ! isset($wpdb) ) {
  1013. /**
  1014. * WordPress Database Object, if it isn't set already in wp-content/db.php
  1015. * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
  1016. * @since 0.71
  1017. */
  1018. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  1019. }
  1020. ?>