PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/class-mysql.php

http://yourls.googlecode.com/
PHP | 925 lines | 541 code | 184 blank | 200 comment | 81 complexity | 8f2b93631dff19424abac47aaa59cd37 MD5 | raw file
  1. <?php
  2. /**********************************************************************
  3. * Author: Justin Vincent (jv@vip.ie)
  4. * Web...: http://justinvincent.com
  5. * Name..: ezSQL
  6. * Desc..: ezSQL Core module - database abstraction library to make
  7. * it very easy to deal with databases. ezSQLcore can not be used by
  8. * itself (it is designed for use by database specific modules).
  9. *
  10. */
  11. /**********************************************************************
  12. * ezSQL Constants
  13. */
  14. define('EZSQL_VERSION','2.17');
  15. define('OBJECT','OBJECT',true);
  16. define('ARRAY_A','ARRAY_A',true);
  17. define('ARRAY_N','ARRAY_N',true);
  18. /**********************************************************************
  19. * Core class containg common functions to manipulate query result
  20. * sets once returned
  21. */
  22. class ezSQLcore
  23. {
  24. var $trace = false; // same as $debug_all
  25. var $debug_all = false; // same as $trace
  26. var $debug_called = false;
  27. var $vardump_called = false;
  28. var $show_errors = true;
  29. var $num_queries = 0;
  30. var $last_query = null;
  31. var $last_error = null;
  32. var $col_info = null;
  33. var $captured_errors = array();
  34. var $cache_dir = false;
  35. var $cache_queries = false;
  36. var $cache_inserts = false;
  37. var $use_disk_cache = false;
  38. var $cache_timeout = 24; // hours
  39. var $timers = array();
  40. var $total_query_time = 0;
  41. var $db_connect_time = 0;
  42. var $trace_log = array();
  43. var $use_trace_log = false;
  44. var $sql_log_file = false;
  45. var $do_profile = false;
  46. var $profile_times = array();
  47. var $all_queries = '';
  48. // == TJH == default now needed for echo of debug function
  49. var $debug_echo_is_on = true;
  50. /**********************************************************************
  51. * Constructor
  52. */
  53. function ezSQLcore()
  54. {
  55. }
  56. /**********************************************************************
  57. * Print SQL/DB error - over-ridden by specific DB class
  58. */
  59. function register_error($err_str)
  60. {
  61. // Keep track of last error
  62. $this->last_error = $err_str;
  63. // Capture all errors to an error array no matter what happens
  64. $this->captured_errors[] = array
  65. (
  66. 'error_str' => $err_str,
  67. 'query' => $this->last_query
  68. );
  69. }
  70. /**********************************************************************
  71. * Turn error handling on or off..
  72. */
  73. function show_errors()
  74. {
  75. $this->show_errors = true;
  76. }
  77. function hide_errors()
  78. {
  79. $this->show_errors = false;
  80. }
  81. /**********************************************************************
  82. * Kill cached query results
  83. */
  84. function flush()
  85. {
  86. // Get rid of these
  87. $this->last_result = null;
  88. $this->col_info = null;
  89. $this->last_query = null;
  90. $this->from_disk_cache = false;
  91. }
  92. /**********************************************************************
  93. * Get one variable from the DB - see docs for more detail
  94. */
  95. function get_var($query=null,$x=0,$y=0)
  96. {
  97. // Log how the function was called
  98. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  99. // If there is a query then perform it if not then use cached results..
  100. if ( $query )
  101. {
  102. $this->query($query);
  103. }
  104. // Extract var out of cached results based x,y vals
  105. if ( $this->last_result[$y] )
  106. {
  107. $values = array_values(get_object_vars($this->last_result[$y]));
  108. }
  109. // If there is a value return it else return null
  110. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  111. }
  112. /**********************************************************************
  113. * Get one row from the DB - see docs for more detail
  114. */
  115. function get_row($query=null,$output=OBJECT,$y=0)
  116. {
  117. // Log how the function was called
  118. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  119. // If there is a query then perform it if not then use cached results..
  120. if ( $query )
  121. {
  122. $this->query($query);
  123. }
  124. // If the output is an object then return object using the row offset..
  125. if ( $output == OBJECT )
  126. {
  127. return $this->last_result[$y]?$this->last_result[$y]:null;
  128. }
  129. // If the output is an associative array then return row as such..
  130. elseif ( $output == ARRAY_A )
  131. {
  132. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  133. }
  134. // If the output is an numerical array then return row as such..
  135. elseif ( $output == ARRAY_N )
  136. {
  137. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  138. }
  139. // If invalid output type was specified..
  140. else
  141. {
  142. $this->show_errors ? trigger_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N",E_USER_WARNING) : null;
  143. }
  144. }
  145. /**********************************************************************
  146. * Function to get 1 column from the cached result set based in X index
  147. * see docs for usage and info
  148. */
  149. function get_col($query=null,$x=0)
  150. {
  151. $new_array = array();
  152. // If there is a query then perform it if not then use cached results..
  153. if ( $query )
  154. {
  155. $this->query($query);
  156. }
  157. // Extract the column values
  158. for ( $i=0; $i < count($this->last_result); $i++ )
  159. {
  160. $new_array[$i] = $this->get_var(null,$x,$i);
  161. }
  162. return $new_array;
  163. }
  164. /**********************************************************************
  165. * Return the the query as a result set - see docs for more details
  166. */
  167. function get_results($query=null, $output = OBJECT)
  168. {
  169. // Log how the function was called
  170. $this->func_call = "\$db->get_results(\"$query\", $output)";
  171. // If there is a query then perform it if not then use cached results..
  172. if ( $query )
  173. {
  174. $this->query($query);
  175. }
  176. // Send back array of objects. Each row is an object
  177. if ( $output == OBJECT )
  178. {
  179. return $this->last_result;
  180. }
  181. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  182. {
  183. if ( $this->last_result )
  184. {
  185. $i=0;
  186. foreach( $this->last_result as $row )
  187. {
  188. $new_array[$i] = get_object_vars($row);
  189. if ( $output == ARRAY_N )
  190. {
  191. $new_array[$i] = array_values($new_array[$i]);
  192. }
  193. $i++;
  194. }
  195. return $new_array;
  196. }
  197. else
  198. {
  199. return null;
  200. }
  201. }
  202. }
  203. /**********************************************************************
  204. * Function to get column meta data info pertaining to the last query
  205. * see docs for more info and usage
  206. */
  207. function get_col_info($info_type="name",$col_offset=-1)
  208. {
  209. if ( $this->col_info )
  210. {
  211. if ( $col_offset == -1 )
  212. {
  213. $i=0;
  214. foreach($this->col_info as $col )
  215. {
  216. $new_array[$i] = $col->{$info_type};
  217. $i++;
  218. }
  219. return $new_array;
  220. }
  221. else
  222. {
  223. return $this->col_info[$col_offset]->{$info_type};
  224. }
  225. }
  226. }
  227. /**********************************************************************
  228. * store_cache
  229. */
  230. function store_cache($query,$is_insert)
  231. {
  232. // The would be cache file for this query
  233. $cache_file = $this->cache_dir.'/'.md5($query);
  234. // disk caching of queries
  235. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
  236. {
  237. if ( ! is_dir($this->cache_dir) )
  238. {
  239. $this->register_error("Could not open cache dir: $this->cache_dir");
  240. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  241. }
  242. else
  243. {
  244. // Cache all result values
  245. $result_cache = array
  246. (
  247. 'col_info' => $this->col_info,
  248. 'last_result' => $this->last_result,
  249. 'num_rows' => $this->num_rows,
  250. 'return_value' => $this->num_rows,
  251. );
  252. file_put_contents($cache_file, serialize($result_cache));
  253. if( file_exists($cache_file . ".updating") )
  254. unlink($cache_file . ".updating");
  255. }
  256. }
  257. }
  258. /**********************************************************************
  259. * get_cache
  260. */
  261. function get_cache($query)
  262. {
  263. // The would be cache file for this query
  264. $cache_file = $this->cache_dir.'/'.md5($query);
  265. // Try to get previously cached version
  266. if ( $this->use_disk_cache && file_exists($cache_file) )
  267. {
  268. // Only use this cache file if less than 'cache_timeout' (hours)
  269. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) &&
  270. !(file_exists($cache_file . ".updating") && (time() - filemtime($cache_file . ".updating") < 60)) )
  271. {
  272. touch($cache_file . ".updating"); // Show that we in the process of updating the cache
  273. }
  274. else
  275. {
  276. $result_cache = unserialize(file_get_contents($cache_file));
  277. $this->col_info = $result_cache['col_info'];
  278. $this->last_result = $result_cache['last_result'];
  279. $this->num_rows = $result_cache['num_rows'];
  280. $this->from_disk_cache = true;
  281. // If debug ALL queries
  282. $this->trace || $this->debug_all ? $this->debug() : null ;
  283. return $result_cache['return_value'];
  284. }
  285. }
  286. }
  287. /**********************************************************************
  288. * Dumps the contents of any input variable to screen in a nicely
  289. * formatted and easy to understand way - any type: Object, Var or Array
  290. */
  291. function vardump($mixed='')
  292. {
  293. // Start outup buffering
  294. ob_start();
  295. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  296. echo "<pre><font face=arial>";
  297. if ( ! $this->vardump_called )
  298. {
  299. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  300. }
  301. $var_type = gettype ($mixed);
  302. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  303. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  304. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  305. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  306. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  307. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  308. echo "\n<hr size=1 noshade color=dddddd>";
  309. // Stop output buffering and capture debug HTML
  310. $html = ob_get_contents();
  311. ob_end_clean();
  312. // Only echo output if it is turned on
  313. if ( $this->debug_echo_is_on )
  314. {
  315. echo $html;
  316. }
  317. $this->vardump_called = true;
  318. return $html;
  319. }
  320. /**********************************************************************
  321. * Alias for the above function
  322. */
  323. function dumpvar($mixed)
  324. {
  325. $this->vardump($mixed);
  326. }
  327. /**********************************************************************
  328. * Displays the last query string that was sent to the database & a
  329. * table listing results (if there were any).
  330. * (abstracted into a seperate file to save server overhead).
  331. */
  332. function debug($print_to_screen=true)
  333. {
  334. // Start outup buffering
  335. ob_start();
  336. echo "<blockquote>";
  337. // Only show ezSQL credits once..
  338. if ( ! $this->debug_called )
  339. {
  340. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  341. }
  342. if ( $this->last_error )
  343. {
  344. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  345. }
  346. if ( $this->from_disk_cache )
  347. {
  348. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  349. }
  350. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  351. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  352. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  353. echo "<blockquote>";
  354. if ( $this->col_info )
  355. {
  356. // =====================================================
  357. // Results top rows
  358. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  359. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  360. for ( $i=0; $i < count($this->col_info); $i++ )
  361. {
  362. echo "<td nowrap align=left valign=top><font size=1 color=555599 face=arial>{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}</font><br><span style='font-family: arial; font-size: 10pt; font-weight: bold;'>{$this->col_info[$i]->name}</span></td>";
  363. }
  364. echo "</tr>";
  365. // ======================================================
  366. // print main results
  367. if ( $this->last_result )
  368. {
  369. $i=0;
  370. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  371. {
  372. $i++;
  373. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  374. foreach ( $one_row as $item )
  375. {
  376. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  377. }
  378. echo "</tr>";
  379. }
  380. } // if last result
  381. else
  382. {
  383. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  384. }
  385. echo "</table>";
  386. } // if col_info
  387. else
  388. {
  389. echo "<font face=arial size=2>No Results</font>";
  390. }
  391. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  392. // Stop output buffering and capture debug HTML
  393. $html = ob_get_contents();
  394. ob_end_clean();
  395. // Only echo output if it is turned on
  396. if ( $this->debug_echo_is_on && $print_to_screen)
  397. {
  398. echo $html;
  399. }
  400. $this->debug_called = true;
  401. return $html;
  402. }
  403. /**********************************************************************
  404. * Naughty little function to ask for some remuniration!
  405. */
  406. function donation()
  407. {
  408. return "<font size=1 face=arial color=000000>If ezSQL has helped <a href=\"https://www.paypal.com/xclick/business=justin%40justinvincent.com&item_name=ezSQL&no_note=1&tax=0\" style=\"color: 0000CC;\">make a donation!?</a> &nbsp;&nbsp;<!--[ go on! you know you want to! ]--></font>";
  409. }
  410. /**********************************************************************
  411. * Timer related functions
  412. */
  413. function timer_get_cur()
  414. {
  415. list($usec, $sec) = explode(" ",microtime());
  416. return ((float)$usec + (float)$sec);
  417. }
  418. function timer_start($timer_name)
  419. {
  420. $this->timers[$timer_name] = $this->timer_get_cur();
  421. }
  422. function timer_elapsed($timer_name)
  423. {
  424. return round($this->timer_get_cur() - $this->timers[$timer_name],2);
  425. }
  426. function timer_update_global($timer_name)
  427. {
  428. if ( $this->do_profile )
  429. {
  430. $this->profile_times[] = array
  431. (
  432. 'query' => $this->last_query,
  433. 'time' => $this->timer_elapsed($timer_name)
  434. );
  435. }
  436. $this->total_query_time += $this->timer_elapsed($timer_name);
  437. }
  438. /**********************************************************************
  439. * Creates a SET nvp sql string from an associative array (and escapes all values)
  440. *
  441. * Usage:
  442. *
  443. * $db_data = array('login'=>'jv','email'=>'jv@vip.ie', 'user_id' => 1, 'created' => 'NOW()');
  444. *
  445. * $db->query("INSERT INTO users SET ".$db->get_set($db_data));
  446. *
  447. * ...OR...
  448. *
  449. * $db->query("UPDATE users SET ".$db->get_set($db_data)." WHERE user_id = 1");
  450. *
  451. * Output:
  452. *
  453. * login = 'jv', email = 'jv@vip.ie', user_id = 1, created = NOW()
  454. */
  455. function get_set($parms)
  456. {
  457. $sql = '';
  458. foreach ( $parms as $field => $val )
  459. {
  460. if ( $val === 'true' ) $val = 1;
  461. if ( $val === 'false' ) $val = 0;
  462. if ( $val == 'NOW()' )
  463. {
  464. $sql .= "$field = ".$this->escape($val).", ";
  465. }
  466. else
  467. {
  468. $sql .= "$field = '".$this->escape($val)."', ";
  469. }
  470. }
  471. return substr($sql,0,-2);
  472. }
  473. }
  474. /**********************************************************************
  475. * Author: Justin Vincent (jv@jvmultimedia.com)
  476. * Web...: http://twitter.com/justinvincent
  477. * Name..: ezSQL_mysql
  478. * Desc..: mySQL component (part of ezSQL databse abstraction library)
  479. *
  480. */
  481. /**********************************************************************
  482. * ezSQL error strings - mySQL
  483. */
  484. $ezsql_mysql_str = array
  485. (
  486. 1 => 'Require $dbuser and $dbpassword to connect to a database server',
  487. 2 => 'Error establishing mySQL database connection. Correct user/password? Correct hostname? Database server running?',
  488. 3 => 'Require $dbname to select a database',
  489. 4 => 'mySQL database connection is not active',
  490. 5 => 'Unexpected error while trying to select database'
  491. );
  492. /**********************************************************************
  493. * ezSQL Database specific class - mySQL
  494. */
  495. if ( ! function_exists ('mysql_connect') ) die('<b>Fatal Error:</b> ezSQL_mysql requires mySQL Lib to be compiled and or linked in to the PHP engine');
  496. if ( ! class_exists ('ezSQLcore') ) die('<b>Fatal Error:</b> ezSQL_mysql requires ezSQLcore (ez_sql_core.php) to be included/loaded before it can be used');
  497. class ezSQL_mysql extends ezSQLcore
  498. {
  499. var $dbuser = false;
  500. var $dbpassword = false;
  501. var $dbname = false;
  502. var $dbhost = false;
  503. var $encoding = false;
  504. /**********************************************************************
  505. * Constructor - allow the user to perform a qucik connect at the
  506. * same time as initialising the ezSQL_mysql class
  507. */
  508. function ezSQL_mysql($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost', $encoding='')
  509. {
  510. $this->dbuser = $dbuser;
  511. $this->dbpassword = $dbpassword;
  512. $this->dbname = $dbname;
  513. $this->dbhost = $dbhost;
  514. $this->encoding = $encoding;
  515. }
  516. /**********************************************************************
  517. * Short hand way to connect to mySQL database server
  518. * and select a mySQL database at the same time
  519. */
  520. function quick_connect($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost', $encoding='')
  521. {
  522. $return_val = false;
  523. if ( ! $this->connect($dbuser, $dbpassword, $dbhost,true) ) ;
  524. else if ( ! $this->select($dbname,$encoding) ) ;
  525. else $return_val = true;
  526. return $return_val;
  527. }
  528. /**********************************************************************
  529. * Try to connect to mySQL database server
  530. */
  531. function connect($dbuser='', $dbpassword='', $dbhost='localhost')
  532. {
  533. global $ezsql_mysql_str; $return_val = false;
  534. // Keep track of how long the DB takes to connect
  535. $this->timer_start('db_connect_time');
  536. // Must have a user and a password
  537. if ( ! $dbuser )
  538. {
  539. $this->register_error($ezsql_mysql_str[1].' in '.__FILE__.' on line '.__LINE__);
  540. $this->show_errors ? trigger_error($ezsql_mysql_str[1],E_USER_WARNING) : null;
  541. }
  542. // Try to establish the server database handle
  543. else if ( ! $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword,true,131074) )
  544. {
  545. $this->register_error($ezsql_mysql_str[2].' in '.__FILE__.' on line '.__LINE__);
  546. $this->show_errors ? trigger_error($ezsql_mysql_str[2],E_USER_WARNING) : null;
  547. }
  548. else
  549. {
  550. $this->dbuser = $dbuser;
  551. $this->dbpassword = $dbpassword;
  552. $this->dbhost = $dbhost;
  553. $return_val = true;
  554. }
  555. return $return_val;
  556. }
  557. /**********************************************************************
  558. * Try to select a mySQL database
  559. */
  560. function select($dbname='', $encoding='')
  561. {
  562. global $ezsql_mysql_str; $return_val = false;
  563. // Must have a database name
  564. if ( ! $dbname )
  565. {
  566. $this->register_error($ezsql_mysql_str[3].' in '.__FILE__.' on line '.__LINE__);
  567. $this->show_errors ? trigger_error($ezsql_mysql_str[3],E_USER_WARNING) : null;
  568. }
  569. // Must have an active database connection
  570. else if ( ! $this->dbh )
  571. {
  572. $this->register_error($ezsql_mysql_str[4].' in '.__FILE__.' on line '.__LINE__);
  573. $this->show_errors ? trigger_error($ezsql_mysql_str[4],E_USER_WARNING) : null;
  574. }
  575. // Try to connect to the database
  576. else if ( !@mysql_select_db($dbname,$this->dbh) )
  577. {
  578. // Try to get error supplied by mysql if not use our own
  579. if ( !$str = @mysql_error($this->dbh))
  580. $str = $ezsql_mysql_str[5];
  581. $this->register_error($str.' in '.__FILE__.' on line '.__LINE__);
  582. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  583. }
  584. else
  585. {
  586. $this->dbname = $dbname;
  587. if($encoding!='')
  588. {
  589. $encoding = strtolower(str_replace("-","",$encoding));
  590. $charsets = array();
  591. $result = mysql_query("SHOW CHARACTER SET");
  592. while($row = mysql_fetch_array($result,MYSQL_ASSOC))
  593. {
  594. $charsets[] = $row["Charset"];
  595. }
  596. if(in_array($encoding,$charsets)){
  597. mysql_query("SET NAMES '".$encoding."'");
  598. }
  599. }
  600. $return_val = true;
  601. }
  602. return $return_val;
  603. }
  604. /**********************************************************************
  605. * Format a mySQL string correctly for safe mySQL insert
  606. * (no mater if magic quotes are on or not)
  607. */
  608. function escape($str)
  609. {
  610. // If there is no existing database connection then try to connect
  611. if ( ! isset($this->dbh) || ! $this->dbh )
  612. {
  613. $this->connect($this->dbuser, $this->dbpassword, $this->dbhost);
  614. $this->select($this->dbname, $this->encoding);
  615. }
  616. return mysql_real_escape_string(stripslashes($str));
  617. }
  618. /**********************************************************************
  619. * Return mySQL specific system date syntax
  620. * i.e. Oracle: SYSDATE Mysql: NOW()
  621. */
  622. function sysdate()
  623. {
  624. return 'NOW()';
  625. }
  626. /**********************************************************************
  627. * Perform mySQL query and try to detirmin result value
  628. */
  629. function query($query)
  630. {
  631. // This keeps the connection alive for very long running scripts
  632. if ( $this->num_queries >= 500 )
  633. {
  634. $this->disconnect();
  635. $this->quick_connect($this->dbuser,$this->dbpassword,$this->dbname,$this->dbhost,$this->encoding);
  636. }
  637. // Initialise return
  638. $return_val = 0;
  639. // Flush cached values..
  640. $this->flush();
  641. // For reg expressions
  642. $query = trim($query);
  643. // Log how the function was called
  644. $this->func_call = "\$db->query(\"$query\")";
  645. // Keep track of the last query for debug..
  646. $this->last_query = $query;
  647. // Count how many queries there have been
  648. $this->num_queries++;
  649. // Keep history of all queries
  650. $this->all_queries .= $query.'<br />';
  651. // Start timer
  652. $this->timer_start($this->num_queries);
  653. // Use core file cache function
  654. if ( $cache = $this->get_cache($query) )
  655. {
  656. // Keep tack of how long all queries have taken
  657. $this->timer_update_global($this->num_queries);
  658. // Trace all queries
  659. if ( $this->use_trace_log )
  660. {
  661. $this->trace_log[] = $this->debug(false);
  662. }
  663. return $cache;
  664. }
  665. // If there is no existing database connection then try to connect
  666. if ( ! isset($this->dbh) || ! $this->dbh )
  667. {
  668. $this->connect($this->dbuser, $this->dbpassword, $this->dbhost);
  669. $this->select($this->dbname,$this->encoding);
  670. }
  671. // Perform the query via std mysql_query function..
  672. $this->result = @mysql_query($query,$this->dbh);
  673. // If there is an error then take note of it..
  674. if ( $str = @mysql_error($this->dbh) )
  675. {
  676. $is_insert = true;
  677. $this->register_error($str);
  678. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  679. return false;
  680. }
  681. // Query was an insert, delete, update, replace
  682. $is_insert = false;
  683. if ( preg_match("/^(insert|delete|update|replace|truncate|drop|create|alter)\s+/i",$query) )
  684. {
  685. $this->rows_affected = @mysql_affected_rows($this->dbh);
  686. // Take note of the insert_id
  687. if ( preg_match("/^(insert|replace)\s+/i",$query) )
  688. {
  689. $this->insert_id = @mysql_insert_id($this->dbh);
  690. }
  691. // Return number fo rows affected
  692. $return_val = $this->rows_affected;
  693. }
  694. // Query was a select
  695. else
  696. {
  697. // Take note of column info
  698. $i=0;
  699. while ($i < @mysql_num_fields($this->result))
  700. {
  701. $this->col_info[$i] = @mysql_fetch_field($this->result);
  702. $i++;
  703. }
  704. // Store Query Results
  705. $num_rows=0;
  706. while ( $row = @mysql_fetch_object($this->result) )
  707. {
  708. // Store relults as an objects within main array
  709. $this->last_result[$num_rows] = $row;
  710. $num_rows++;
  711. }
  712. @mysql_free_result($this->result);
  713. // Log number of rows the query returned
  714. $this->num_rows = $num_rows;
  715. // Return number of rows selected
  716. $return_val = $this->num_rows;
  717. }
  718. // disk caching of queries
  719. $this->store_cache($query,$is_insert);
  720. // If debug ALL queries
  721. $this->trace || $this->debug_all ? $this->debug() : null ;
  722. // Keep tack of how long all queries have taken
  723. $this->timer_update_global($this->num_queries);
  724. // Trace all queries
  725. if ( $this->use_trace_log )
  726. {
  727. $this->trace_log[] = $this->debug(false);
  728. }
  729. return $return_val;
  730. }
  731. /**********************************************************************
  732. * Close the active mySQL connection
  733. */
  734. function disconnect()
  735. {
  736. @mysql_close($this->dbh);
  737. }
  738. function mysql_version() {
  739. return mysql_get_server_info( $this->dbh ) ;
  740. }
  741. }