5 * @version $Id: mysql.php,v 1.5 2006/02/10 01:30:19 scronide Exp $
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('SQL_LAYER'))
17 define('SQL_LAYER', 'mysql');
21 * MySQL Database Abstraction Layer
22 * Minimum Requirement is 3.23+/4.0+/4.1+
28 var $return_on_error = false;
29 var $transaction = false;
32 var $open_queries = array();
34 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false)
36 $this->persistency = $persistency;
37 $this->user = $sqluser;
38 $this->server = $sqlserver . (($port) ? ':' . $port : '');
39 $this->dbname = $database;
41 $this->db_connect_id = ($this->persistency) ? @mysql_pconnect($this->server, $this->user, $sqlpassword) : @mysql_connect($this->server, $this->user, $sqlpassword);
43 if ($this->db_connect_id && $this->dbname != '')
45 if (@mysql_select_db($this->dbname))
47 return $this->db_connect_id;
51 return $this->sql_error('');
59 if (!$this->db_connect_id)
64 if (sizeof($this->open_queries))
66 foreach ($this->open_queries as $i_query_id => $query_id)
68 @mysql_free_result($query_id);
72 return @mysql_close($this->db_connect_id);
75 function sql_return_on_error($fail = false)
77 $this->return_on_error = $fail;
80 function sql_num_queries()
82 return $this->num_queries;
85 function sql_transaction($status = 'begin')
90 $result = @mysql_query('BEGIN', $this->db_connect_id);
91 $this->transaction = true;
95 $result = @mysql_query('COMMIT', $this->db_connect_id);
96 $this->transaction = false;
100 @mysql_query('ROLLBACK', $this->db_connect_id);
105 $result = @mysql_query('ROLLBACK', $this->db_connect_id);
106 $this->transaction = false;
117 function sql_query($query = '', $cache_ttl = 0)
123 // EXPLAIN only in extra debug mode
124 if (defined('DEBUG_EXTRA'))
126 $this->sql_report('start', $query);
129 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
131 if (!$this->query_result)
133 $this->num_queries++;
135 if (($this->query_result = @mysql_query($query, $this->db_connect_id)) === false)
137 $this->sql_error($query);
140 if (defined('DEBUG_EXTRA'))
142 $this->sql_report('stop', $query);
145 if ($cache_ttl && method_exists($cache, 'sql_save'))
147 $this->open_queries[(int) $this->query_result] = $this->query_result;
148 $cache->sql_save($query, $this->query_result, $cache_ttl);
149 // mysql_free_result called within sql_save()
151 else if (strpos($query, 'SELECT') !== false && $this->query_result)
153 $this->open_queries[(int) $this->query_result] = $this->query_result;
156 else if (defined('DEBUG_EXTRA'))
158 $this->sql_report('fromcache', $query);
166 return ($this->query_result) ? $this->query_result : false;
169 function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) {
171 $this->query_result = false;
173 // only limit the number of rows if $total is greater than 0
175 $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total);
177 return $this->sql_query($query, $cache_ttl);
183 // Idea for this from Ikonboard
184 function sql_build_array($query, $assoc_ary = false)
186 if (!is_array($assoc_ary))
193 if ($query == 'INSERT')
195 foreach ($assoc_ary as $key => $var)
203 elseif (is_string($var))
205 $values[] = "'" . $this->sql_escape($var) . "'";
209 $values[] = (is_bool($var)) ? intval($var) : $var;
213 $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
215 else if ($query == 'UPDATE' || $query == 'SELECT')
218 foreach ($assoc_ary as $key => $var)
222 $values[] = "$key = NULL";
224 elseif (is_string($var))
226 $values[] = "$key = '" . $this->sql_escape($var) . "'";
230 $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
233 $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
239 // Other query methods
241 // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
242 // don't want this here by a middle Milestone
243 function sql_numrows($query_id = false)
247 $query_id = $this->query_result;
250 return ($query_id) ? @mysql_num_rows($query_id) : false;
253 function sql_affectedrows()
255 return ($this->db_connect_id) ? @mysql_affected_rows($this->db_connect_id) : false;
258 function sql_fetchrow($query_id = false)
264 $query_id = $this->query_result;
267 if (isset($cache->sql_rowset[$query_id]))
269 return $cache->sql_fetchrow($query_id);
272 return ($query_id) ? @mysql_fetch_assoc($query_id) : false;
275 function sql_fetchrowset($query_id = false)
279 $query_id = $this->query_result;
284 unset($this->rowset[$query_id]);
285 unset($this->row[$query_id]);
288 while ($this->rowset[$query_id] = $this->sql_fetchrow($query_id))
290 $result[] = $this->rowset[$query_id];
298 function sql_fetchfield($field, $rownum = -1, $query_id = false)
302 $query_id = $this->query_result;
309 $result = @mysql_result($query_id, $rownum, $field);
313 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
315 if ($this->sql_fetchrow($query_id))
317 $result = $this->row[$query_id][$field];
322 if ($this->rowset[$query_id])
324 $result = $this->rowset[$query_id][$field];
326 elseif ($this->row[$query_id])
328 $result = $this->row[$query_id][$field];
337 function sql_rowseek($rownum, $query_id = false)
341 $query_id = $this->query_result;
344 return ($query_id) ? @mysql_data_seek($query_id, $rownum) : false;
347 function sql_nextid()
349 return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false;
352 function sql_freeresult($query_id = false)
356 $query_id = $this->query_result;
359 if (isset($this->open_queries[(int) $query_id]))
361 unset($this->open_queries[(int) $query_id]);
362 return @mysql_free_result($query_id);
368 function sql_escape($msg) {
369 if (function_exists('mysql_real_escape_string')) {
370 return @mysql_real_escape_string($msg, $this->db_connect_id);
372 return mysql_escape_string($msg);
376 function sql_error($sql = '')
378 if (!$this->return_on_error)
380 $this_page = (isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
381 $this_page .= '&' . ((isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : (isset($_ENV['QUERY_STRING']) ? $_ENV['QUERY_STRING'] : ''));
383 $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @mysql_error() . '<br /><br /><u>CALLING PAGE</u><br /><br />' . htmlspecialchars($this_page) . (($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
385 if ($this->transaction)
387 $this->sql_transaction('rollback');
390 trigger_error($message, E_USER_ERROR);
394 'message' => @mysql_error(),
395 'code' => @mysql_errno()
401 function sql_report($mode, $query = '')
403 if (empty($_GET['explain']))
408 global $db, $cache, $starttime, $phpbb_root_path;
409 static $curtime, $query_hold, $html_hold;
410 static $sql_report = '';
411 static $cache_num_queries = 0;
413 if (!$query && !empty($query_hold))
415 $query = $query_hold;
427 $mtime = explode(' ', microtime());
428 $totaltime = $mtime[0] + $mtime[1] - $starttime;
430 echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8869-1"><meta http-equiv="Content-Style-Type" content="text/css"><link rel="stylesheet" href="' . $phpbb_root_path . 'adm/subSilver.css" type="text/css"><style type="text/css">' . "\n";
431 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
432 echo 'td.cat { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
433 echo '</style><title>' . $msg_title . '</title></head><body>';
434 echo '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><a href="' . htmlspecialchars(preg_replace('/&explain=([^&]*)/', '', $_SERVER['REQUEST_URI'])) . '"><img src="' . $phpbb_root_path . 'adm/images/header_left.jpg" width="200" height="60" alt="phpBB Logo" title="phpBB Logo" border="0"/></a></td><td width="100%" background="' . $phpbb_root_path . 'adm/images/header_bg.jpg" height="60" align="right" nowrap="nowrap"><span class="maintitle">SQL Report</span> </td></tr></table><br clear="all"/><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td height="40" align="center" valign="middle"><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries} queries" . (($cache_num_queries) ? " + $cache_num_queries " . (($cache_num_queries == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></td></tr><tr><td align="center" nowrap="nowrap">Time spent on MySQL queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></td></tr></table><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td>';
436 echo '</td></tr></table><br /></body></html>';
441 $query_hold = $query;
444 $explain_query = $query;
445 if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
447 $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
449 elseif (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
451 $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
454 if (preg_match('/^SELECT/', $explain_query))
458 if ($result = mysql_query("EXPLAIN $explain_query", $this->db_connect_id))
460 while ($row = mysql_fetch_assoc($result))
462 if (!$html_table && sizeof($row))
465 $html_hold .= '<table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0" align="center"><tr>';
467 foreach (array_keys($row) as $val)
469 $html_hold .= '<th nowrap="nowrap">' . (($val) ? ucwords(str_replace('_', ' ', $val)) : ' ') . '</th>';
471 $html_hold .= '</tr>';
473 $html_hold .= '<tr>';
476 foreach (array_values($row) as $val)
478 $class = ($class == 'row1') ? 'row2' : 'row1';
479 $html_hold .= '<td class="' . $class . '">' . (($val) ? $val : ' ') . '</td>';
481 $html_hold .= '</tr>';
487 $html_hold .= '</table>';
491 $curtime = explode(' ', microtime());
492 $curtime = $curtime[0] + $curtime[1];
496 $endtime = explode(' ', microtime());
497 $endtime = $endtime[0] + $endtime[1];
499 $result = mysql_query($query, $this->db_connect_id);
500 while ($void = mysql_fetch_assoc($result))
502 // Take the time spent on parsing rows into account
504 $splittime = explode(' ', microtime());
505 $splittime = $splittime[0] + $splittime[1];
507 $time_cache = $endtime - $curtime;
508 $time_db = $splittime - $endtime;
509 $color = ($time_db > $time_cache) ? 'green' : 'red';
511 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query results obtained from the cache</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table><p align="center">';
513 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p>';
515 // Pad the start time to not interfere with page timing
516 $starttime += $time_db;
518 mysql_free_result($result);
519 $cache_num_queries++;
523 $endtime = explode(' ', microtime());
524 $endtime = $endtime[0] + $endtime[1];
526 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query #' . $this->num_queries . '</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table> ' . $html_hold . '<p align="center">';
528 if ($this->query_result)
530 if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
532 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
534 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
538 $error = $this->sql_error();
539 $sql_report .= '<b style="color: red">FAILED</b> - MySQL Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
542 $sql_report .= '</p>';
544 $this->sql_time += $endtime - $curtime;