5 // Justin Vincent (justin@visunet.ie)
6 // http://php.justinvincent.com
8 define('EZSQL_VERSION', 'WP1.25');
9 define('OBJECT', 'OBJECT', true);
10 define('ARRAY_A', 'ARRAY_A', false);
11 define('ARRAY_N', 'ARRAY_N', false);
13 if (!defined('SAVEQUERIES'))
14 define('SAVEQUERIES', false);
18 var $show_errors = false;
36 var $optiongroup_options;
41 var $term_relationships;
47 * Connects to the database server and selects a database
48 * @param string $dbuser
49 * @param string $dbpassword
50 * @param string $dbname
51 * @param string $dbhost
53 function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
54 return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
57 function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
58 register_shutdown_function(array(&$this, "__destruct"));
60 if ( defined('WP_DEBUG') and WP_DEBUG == true )
63 if ( defined('DB_CHARSET') )
64 $this->charset = DB_CHARSET;
66 if ( defined('DB_COLLATE') )
67 $this->collate = DB_COLLATE;
69 $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
72 <h1>Error establishing a database connection</h1>
73 <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>
75 <li>Are you sure you have the correct username and password?</li>
76 <li>Are you sure that you have typed the correct hostname?</li>
77 <li>Are you sure that the database server is running?</li>
79 <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>
86 if ( !empty($this->charset) && version_compare(mysql_get_server_info(), '4.1.0', '>=') )
87 $this->query("SET NAMES '$this->charset'");
89 $this->select($dbname);
92 function __destruct() {
97 * Selects a database using the current class's $this->dbh
98 * @param string $db name
100 function select($db) {
101 if (!@mysql_select_db($db, $this->dbh)) {
102 $this->ready = false;
104 <h1>Can’t select database</h1>
105 <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>
107 <li>Are you sure it exists?</li>
108 <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
109 <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>
111 <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>");
117 * Escapes content for insertion into the database, for security
119 * @param string $string
120 * @return string query safe string
122 function escape($string) {
123 return addslashes( $string ); // Disable rest for now, causing problems
124 if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
125 return mysql_escape_string( $string );
127 return mysql_real_escape_string( $string, $this->dbh );
131 * Escapes content by reference for insertion into the database, for security
134 function escape_by_ref(&$s) {
135 $s = $this->escape($s);
139 * Prepares a SQL query for safe use, using sprintf() syntax
141 function prepare($args=NULL) {
142 if ( NULL === $args )
144 $args = func_get_args();
145 $query = array_shift($args);
146 $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
147 $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
148 $query = str_replace('%s', "'%s'", $query); // quote the strings
149 array_walk($args, array(&$this, 'escape_by_ref'));
150 return @vsprintf($query, $args);
153 // ==================================================================
154 // Print SQL/DB error.
156 function print_error($str = '') {
158 if (!$str) $str = mysql_error($this->dbh);
160 array ('query' => $this->last_query, 'error_str' => $str);
162 $error_str = "WordPress database error $str for query $this->last_query";
163 error_log($error_str, 0);
165 // Is error output turned on or not..
166 if ( !$this->show_errors )
169 $str = htmlspecialchars($str, ENT_QUOTES);
170 $query = htmlspecialchars($this->last_query, ENT_QUOTES);
172 // If there is an error then take note of it
173 print "<div id='error'>
174 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
175 <code>$query</code></p>
179 // ==================================================================
180 // Turn error handling on or off..
182 function show_errors( $show = true ) {
183 $errors = $this->show_errors;
184 $this->show_errors = $show;
188 function hide_errors() {
189 $show = $this->show_errors;
190 $this->show_errors = false;
194 // ==================================================================
195 // Kill cached query results
198 $this->last_result = array();
199 $this->col_info = null;
200 $this->last_query = null;
203 // ==================================================================
204 // Basic Query - see docs for more detail
206 function query($query) {
207 if ( ! $this->ready )
210 // filter the query, if filters are available
211 // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
212 if ( function_exists('apply_filters') )
213 $query = apply_filters('query', $query);
219 // Log how the function was called
220 $this->func_call = "\$db->query(\"$query\")";
222 // Keep track of the last query for debug..
223 $this->last_query = $query;
225 // Perform the query via std mysql_query function..
227 $this->timer_start();
229 $this->result = @mysql_query($query, $this->dbh);
230 ++$this->num_queries;
233 $this->queries[] = array( $query, $this->timer_stop() );
235 // If there is an error then take note of it..
236 if ( mysql_error($this->dbh) ) {
237 $this->print_error();
241 if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
242 $this->rows_affected = mysql_affected_rows($this->dbh);
243 // Take note of the insert_id
244 if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
245 $this->insert_id = mysql_insert_id($this->dbh);
247 // Return number of rows affected
248 $return_val = $this->rows_affected;
251 while ($i < @mysql_num_fields($this->result)) {
252 $this->col_info[$i] = @mysql_fetch_field($this->result);
256 while ( $row = @mysql_fetch_object($this->result) ) {
257 $this->last_result[$num_rows] = $row;
261 @mysql_free_result($this->result);
263 // Log number of rows the query returned
264 $this->num_rows = $num_rows;
266 // Return number of rows selected
267 $return_val = $this->num_rows;
274 * Get one variable from the database
275 * @param string $query (can be null as well, for caching, see codex)
276 * @param int $x = 0 row num to return
277 * @param int $y = 0 col num to return
278 * @return mixed results
280 function get_var($query=null, $x = 0, $y = 0) {
281 $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
283 $this->query($query);
285 // Extract var out of cached results based x,y vals
286 if ( $this->last_result[$y] ) {
287 $values = array_values(get_object_vars($this->last_result[$y]));
290 // If there is a value return it else return null
291 return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
295 * Get one row from the database
296 * @param string $query
297 * @param string $output ARRAY_A | ARRAY_N | OBJECT
298 * @param int $y row num to return
299 * @return mixed results
301 function get_row($query = null, $output = OBJECT, $y = 0) {
302 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
304 $this->query($query);
308 if ( !isset($this->last_result[$y]) )
311 if ( $output == OBJECT ) {
312 return $this->last_result[$y] ? $this->last_result[$y] : null;
313 } elseif ( $output == ARRAY_A ) {
314 return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
315 } elseif ( $output == ARRAY_N ) {
316 return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
318 $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
323 * Gets one column from the database
324 * @param string $query (can be null as well, for caching, see codex)
325 * @param int $x col num to return
326 * @return array results
328 function get_col($query = null , $x = 0) {
330 $this->query($query);
332 $new_array = array();
333 // Extract the column values
334 for ( $i=0; $i < count($this->last_result); $i++ ) {
335 $new_array[$i] = $this->get_var(null, $x, $i);
341 * Return an entire result set from the database
342 * @param string $query (can also be null to pull from the cache)
343 * @param string $output ARRAY_A | ARRAY_N | OBJECT
344 * @return mixed results
346 function get_results($query = null, $output = OBJECT) {
347 $this->func_call = "\$db->get_results(\"$query\", $output)";
350 $this->query($query);
354 // Send back array of objects. Each row is an object
355 if ( $output == OBJECT ) {
356 return $this->last_result;
357 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
358 if ( $this->last_result ) {
360 foreach( $this->last_result as $row ) {
361 $new_array[$i] = (array) $row;
362 if ( $output == ARRAY_N ) {
363 $new_array[$i] = array_values($new_array[$i]);
375 * Grabs column metadata from the last query
376 * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
377 * @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
378 * @return mixed results
380 function get_col_info($info_type = 'name', $col_offset = -1) {
381 if ( $this->col_info ) {
382 if ( $col_offset == -1 ) {
384 foreach($this->col_info as $col ) {
385 $new_array[$i] = $col->{$info_type};
390 return $this->col_info[$col_offset]->{$info_type};
396 * Starts the timer, for debugging purposes
398 function timer_start() {
399 $mtime = microtime();
400 $mtime = explode(' ', $mtime);
401 $this->time_start = $mtime[1] + $mtime[0];
406 * Stops the debugging timer
407 * @return int total time spent on the query, in milliseconds
409 function timer_stop() {
410 $mtime = microtime();
411 $mtime = explode(' ', $mtime);
412 $time_end = $mtime[1] + $mtime[0];
413 $time_total = $time_end - $this->time_start;
418 * Wraps fatal errors in a nice header and footer and dies.
419 * @param string $message
421 function bail($message) { // Just wraps errors in a nice header and footer
422 if ( !$this->show_errors ) {
423 if ( class_exists('WP_Error') )
424 $this->error = new WP_Error('500', $message);
426 $this->error = $message;
433 if ( ! isset($wpdb) )
434 $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);