5 // Justin Vincent (justin@visunet.ie)
6 // http://php.justinvincent.com
8 define('EZSQL_VERSION', 'WP1.25');
9 define('OBJECT', 'OBJECT', true);
10 define('OBJECT_K', 'OBJECT_K', false);
11 define('ARRAY_A', 'ARRAY_A', false);
12 define('ARRAY_N', 'ARRAY_N', false);
14 if (!defined('SAVEQUERIES'))
15 define('SAVEQUERIES', false);
19 var $show_errors = false;
20 var $suppress_errors = false;
41 var $term_relationships;
42 var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
43 'postmeta', 'terms', 'term_taxonomy', 'term_relationships');
48 * Connects to the database server and selects a database
49 * @param string $dbuser
50 * @param string $dbpassword
51 * @param string $dbname
52 * @param string $dbhost
54 function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
55 return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
58 function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
59 register_shutdown_function(array(&$this, "__destruct"));
61 if ( defined('WP_DEBUG') and WP_DEBUG == true )
64 if ( defined('DB_CHARSET') )
65 $this->charset = DB_CHARSET;
67 if ( defined('DB_COLLATE') )
68 $this->collate = DB_COLLATE;
70 $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
73 <h1>Error establishing a database connection</h1>
74 <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>$dbhost</code>. This could mean your host's database server is down.</p>
76 <li>Are you sure you have the correct username and password?</li>
77 <li>Are you sure that you have typed the correct hostname?</li>
78 <li>Are you sure that the database server is running?</li>
80 <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>
87 if ( !empty($this->charset) && version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') )
88 $this->query("SET NAMES '$this->charset'");
90 $this->select($dbname);
93 function __destruct() {
97 function set_prefix($prefix) {
99 if ( preg_match('|[^a-z0-9_]|i', $prefix) )
100 return new WP_Error('invalid_db_prefix', 'Invalid database prefix'); // No gettext here
102 $old_prefix = $this->prefix;
103 $this->prefix = $prefix;
105 foreach ( $this->tables as $table )
106 $this->$table = $this->prefix . $table;
108 if ( defined('CUSTOM_USER_TABLE') )
109 $this->users = CUSTOM_USER_TABLE;
111 if ( defined('CUSTOM_USER_META_TABLE') )
112 $this->usermeta = CUSTOM_USER_META_TABLE;
118 * Selects a database using the current class's $this->dbh
119 * @param string $db name
121 function select($db) {
122 if (!@mysql_select_db($db, $this->dbh)) {
123 $this->ready = false;
125 <h1>Can’t select database</h1>
126 <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>$db</code> database.</p>
128 <li>Are you sure it exists?</li>
129 <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
130 <li>On some systems the name of your database is prefixed with your username, so it would be like username_wordpress. Could that be the problem?</li>
132 <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>");
138 * Escapes content for insertion into the database, for security
140 * @param string $string
141 * @return string query safe string
143 function escape($string) {
144 return addslashes( $string );
145 // Disable rest for now, causing problems
147 if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
148 return mysql_escape_string( $string );
150 return mysql_real_escape_string( $string, $this->dbh );
155 * Escapes content by reference for insertion into the database, for security
158 function escape_by_ref(&$s) {
159 $s = $this->escape($s);
163 * Prepares a SQL query for safe use, using sprintf() syntax
165 function prepare($args=NULL) {
166 if ( NULL === $args )
168 $args = func_get_args();
169 $query = array_shift($args);
170 $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
171 $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
172 $query = str_replace('%s', "'%s'", $query); // quote the strings
173 array_walk($args, array(&$this, 'escape_by_ref'));
174 return @vsprintf($query, $args);
177 // ==================================================================
178 // Print SQL/DB error.
180 function print_error($str = '') {
183 if (!$str) $str = mysql_error($this->dbh);
185 array ('query' => $this->last_query, 'error_str' => $str);
187 if ( $this->suppress_errors )
190 $error_str = "WordPress database error $str for query $this->last_query";
191 if ( $caller = $this->get_caller() )
192 $error_str .= " made by $caller";
195 if ( ! function_exists('error_log') )
198 $log_file = @ini_get('error_log');
199 if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
203 @error_log($error_str, 0);
205 // Is error output turned on or not..
206 if ( !$this->show_errors )
209 $str = htmlspecialchars($str, ENT_QUOTES);
210 $query = htmlspecialchars($this->last_query, ENT_QUOTES);
212 // If there is an error then take note of it
213 print "<div id='error'>
214 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
215 <code>$query</code></p>
219 // ==================================================================
220 // Turn error handling on or off..
222 function show_errors( $show = true ) {
223 $errors = $this->show_errors;
224 $this->show_errors = $show;
228 function hide_errors() {
229 $show = $this->show_errors;
230 $this->show_errors = false;
234 function suppress_errors( $suppress = true ) {
235 $errors = $this->suppress_errors;
236 $this->suppress_errors = $suppress;
240 // ==================================================================
241 // Kill cached query results
244 $this->last_result = array();
245 $this->col_info = null;
246 $this->last_query = null;
249 // ==================================================================
250 // Basic Query - see docs for more detail
252 function query($query) {
253 if ( ! $this->ready )
256 // filter the query, if filters are available
257 // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
258 if ( function_exists('apply_filters') )
259 $query = apply_filters('query', $query);
265 // Log how the function was called
266 $this->func_call = "\$db->query(\"$query\")";
268 // Keep track of the last query for debug..
269 $this->last_query = $query;
271 // Perform the query via std mysql_query function..
273 $this->timer_start();
275 $this->result = @mysql_query($query, $this->dbh);
276 ++$this->num_queries;
279 $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
281 // If there is an error then take note of it..
282 if ( $this->last_error = mysql_error($this->dbh) ) {
283 $this->print_error();
287 if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
288 $this->rows_affected = mysql_affected_rows($this->dbh);
289 // Take note of the insert_id
290 if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
291 $this->insert_id = mysql_insert_id($this->dbh);
293 // Return number of rows affected
294 $return_val = $this->rows_affected;
297 while ($i < @mysql_num_fields($this->result)) {
298 $this->col_info[$i] = @mysql_fetch_field($this->result);
302 while ( $row = @mysql_fetch_object($this->result) ) {
303 $this->last_result[$num_rows] = $row;
307 @mysql_free_result($this->result);
309 // Log number of rows the query returned
310 $this->num_rows = $num_rows;
312 // Return number of rows selected
313 $return_val = $this->num_rows;
320 * Insert an array of data into a table
321 * @param string $table WARNING: not sanitized!
322 * @param array $data should not already be SQL-escaped
323 * @return mixed results of $this->query()
325 function insert($table, $data) {
326 $data = add_magic_quotes($data);
327 $fields = array_keys($data);
328 return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
332 * Update a row in the table with an array of data
333 * @param string $table WARNING: not sanitized!
334 * @param array $data should not already be SQL-escaped
335 * @param array $where a named array of WHERE column => value relationships. Multiple member pairs will be joined with ANDs. WARNING: the column names are not currently sanitized!
336 * @return mixed results of $this->query()
338 function update($table, $data, $where){
339 $data = add_magic_quotes($data);
340 $bits = $wheres = array();
341 foreach ( array_keys($data) as $k )
342 $bits[] = "`$k` = '$data[$k]'";
344 if ( is_array( $where ) )
345 foreach ( $where as $c => $v )
346 $wheres[] = "$c = '" . $this->escape( $v ) . "'";
349 return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
353 * Get one variable from the database
354 * @param string $query (can be null as well, for caching, see codex)
355 * @param int $x = 0 row num to return
356 * @param int $y = 0 col num to return
357 * @return mixed results
359 function get_var($query=null, $x = 0, $y = 0) {
360 $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
362 $this->query($query);
364 // Extract var out of cached results based x,y vals
365 if ( !empty( $this->last_result[$y] ) ) {
366 $values = array_values(get_object_vars($this->last_result[$y]));
369 // If there is a value return it else return null
370 return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
374 * Get one row from the database
375 * @param string $query
376 * @param string $output ARRAY_A | ARRAY_N | OBJECT
377 * @param int $y row num to return
378 * @return mixed results
380 function get_row($query = null, $output = OBJECT, $y = 0) {
381 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
383 $this->query($query);
387 if ( !isset($this->last_result[$y]) )
390 if ( $output == OBJECT ) {
391 return $this->last_result[$y] ? $this->last_result[$y] : null;
392 } elseif ( $output == ARRAY_A ) {
393 return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
394 } elseif ( $output == ARRAY_N ) {
395 return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
397 $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
402 * Gets one column from the database
403 * @param string $query (can be null as well, for caching, see codex)
404 * @param int $x col num to return
405 * @return array results
407 function get_col($query = null , $x = 0) {
409 $this->query($query);
411 $new_array = array();
412 // Extract the column values
413 for ( $i=0; $i < count($this->last_result); $i++ ) {
414 $new_array[$i] = $this->get_var(null, $x, $i);
420 * Return an entire result set from the database
421 * @param string $query (can also be null to pull from the cache)
422 * @param string $output ARRAY_A | ARRAY_N | OBJECT_K | OBJECT
423 * @return mixed results
425 function get_results($query = null, $output = OBJECT) {
426 $this->func_call = "\$db->get_results(\"$query\", $output)";
429 $this->query($query);
433 if ( $output == OBJECT ) {
434 // Return an integer-keyed array of row objects
435 return $this->last_result;
436 } elseif ( $output == OBJECT_K ) {
437 // Return an array of row objects with keys from column 1
438 // (Duplicates are discarded)
439 foreach ( $this->last_result as $row ) {
440 $key = array_shift( get_object_vars( $row ) );
441 if ( !isset( $new_array[ $key ] ) )
442 $new_array[ $key ] = $row;
445 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
446 // Return an integer-keyed array of...
447 if ( $this->last_result ) {
449 foreach( $this->last_result as $row ) {
450 if ( $output == ARRAY_N ) {
451 // ...integer-keyed row arrays
452 $new_array[$i] = array_values( get_object_vars( $row ) );
454 // ...column name-keyed row arrays
455 $new_array[$i] = get_object_vars( $row );
465 * Grabs column metadata from the last query
466 * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
467 * @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
468 * @return mixed results
470 function get_col_info($info_type = 'name', $col_offset = -1) {
471 if ( $this->col_info ) {
472 if ( $col_offset == -1 ) {
474 foreach($this->col_info as $col ) {
475 $new_array[$i] = $col->{$info_type};
480 return $this->col_info[$col_offset]->{$info_type};
486 * Starts the timer, for debugging purposes
488 function timer_start() {
489 $mtime = microtime();
490 $mtime = explode(' ', $mtime);
491 $this->time_start = $mtime[1] + $mtime[0];
496 * Stops the debugging timer
497 * @return int total time spent on the query, in milliseconds
499 function timer_stop() {
500 $mtime = microtime();
501 $mtime = explode(' ', $mtime);
502 $time_end = $mtime[1] + $mtime[0];
503 $time_total = $time_end - $this->time_start;
508 * Wraps fatal errors in a nice header and footer and dies.
509 * @param string $message
511 function bail($message) { // Just wraps errors in a nice header and footer
512 if ( !$this->show_errors ) {
513 if ( class_exists('WP_Error') )
514 $this->error = new WP_Error('500', $message);
516 $this->error = $message;
523 * Checks wether of not the database version is high enough to support the features WordPress uses
524 * @global $wp_version
526 function check_database_version()
529 // Make sure the server has MySQL 4.0
530 $mysql_version = preg_replace('|[^0-9\.]|', '', @mysql_get_server_info($this->dbh));
531 if ( version_compare($mysql_version, '4.0.0', '<') )
532 return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
536 * This function is called when WordPress is generating the table schema to determine wether or not the current database
537 * supports or needs the collation statements.
539 function supports_collation()
541 return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
545 * Get the name of the function that called wpdb.
546 * @return string the name of the calling function
548 function get_caller() {
550 if ( !is_callable('debug_backtrace') )
553 $bt = debug_backtrace();
556 foreach ( $bt as $trace ) {
557 if ( @$trace['class'] == __CLASS__ )
559 elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
561 elseif ( strtolower(@$trace['function']) == 'apply_filters' )
563 elseif ( strtolower(@$trace['function']) == 'do_action' )
566 $caller = $trace['function'];
574 if ( ! isset($wpdb) )
575 $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);