PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/source/mydroid/external/webkit/WebKitSite/blog/wp-includes/wp-db.php

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