PageRenderTime 56ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/shared/ez_sql_core.php

https://github.com/OmegaVersion/ezSQL
PHP | 622 lines | 372 code | 122 blank | 128 comment | 53 complexity | 70214d6057184a92ef9dcce59888f273 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. // == TJH == default now needed for echo of debug function
  48. var $debug_echo_is_on = true;
  49. /**********************************************************************
  50. * Constructor
  51. */
  52. function ezSQLcore()
  53. {
  54. }
  55. /**********************************************************************
  56. * Get host and port from an "host:port" notation.
  57. * Returns array of host and port. If port is omitted, returns $default
  58. */
  59. function get_host_port( $host, $default = false )
  60. {
  61. $port = $default;
  62. if ( false !== strpos( $host, ':' ) ) {
  63. list( $host, $port ) = explode( ':', $host );
  64. $port = (int) $port;
  65. }
  66. return array( $host, $port );
  67. }
  68. /**********************************************************************
  69. * Print SQL/DB error - over-ridden by specific DB class
  70. */
  71. function register_error($err_str)
  72. {
  73. // Keep track of last error
  74. $this->last_error = $err_str;
  75. // Capture all errors to an error array no matter what happens
  76. $this->captured_errors[] = array
  77. (
  78. 'error_str' => $err_str,
  79. 'query' => $this->last_query
  80. );
  81. }
  82. /**********************************************************************
  83. * Turn error handling on or off..
  84. */
  85. function show_errors()
  86. {
  87. $this->show_errors = true;
  88. }
  89. function hide_errors()
  90. {
  91. $this->show_errors = false;
  92. }
  93. /**********************************************************************
  94. * Kill cached query results
  95. */
  96. function flush()
  97. {
  98. // Get rid of these
  99. $this->last_result = null;
  100. $this->col_info = null;
  101. $this->last_query = null;
  102. $this->from_disk_cache = false;
  103. }
  104. /**********************************************************************
  105. * Get one variable from the DB - see docs for more detail
  106. */
  107. function get_var($query=null,$x=0,$y=0)
  108. {
  109. // Log how the function was called
  110. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  111. // If there is a query then perform it if not then use cached results..
  112. if ( $query )
  113. {
  114. $this->query($query);
  115. }
  116. // Extract var out of cached results based x,y vals
  117. if ( $this->last_result[$y] )
  118. {
  119. $values = array_values(get_object_vars($this->last_result[$y]));
  120. }
  121. // If there is a value return it else return null
  122. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  123. }
  124. /**********************************************************************
  125. * Get one row from the DB - see docs for more detail
  126. */
  127. function get_row($query=null,$output=OBJECT,$y=0)
  128. {
  129. // Log how the function was called
  130. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  131. // If there is a query then perform it if not then use cached results..
  132. if ( $query )
  133. {
  134. $this->query($query);
  135. }
  136. // If the output is an object then return object using the row offset..
  137. if ( $output == OBJECT )
  138. {
  139. return $this->last_result[$y]?$this->last_result[$y]:null;
  140. }
  141. // If the output is an associative array then return row as such..
  142. elseif ( $output == ARRAY_A )
  143. {
  144. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  145. }
  146. // If the output is an numerical array then return row as such..
  147. elseif ( $output == ARRAY_N )
  148. {
  149. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  150. }
  151. // If invalid output type was specified..
  152. else
  153. {
  154. $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;
  155. }
  156. }
  157. /**********************************************************************
  158. * Function to get 1 column from the cached result set based in X index
  159. * see docs for usage and info
  160. */
  161. function get_col($query=null,$x=0)
  162. {
  163. $new_array = array();
  164. // If there is a query then perform it if not then use cached results..
  165. if ( $query )
  166. {
  167. $this->query($query);
  168. }
  169. // Extract the column values
  170. for ( $i=0; $i < count($this->last_result); $i++ )
  171. {
  172. $new_array[$i] = $this->get_var(null,$x,$i);
  173. }
  174. return $new_array;
  175. }
  176. /**********************************************************************
  177. * Return the the query as a result set - see docs for more details
  178. */
  179. function get_results($query=null, $output = OBJECT)
  180. {
  181. // Log how the function was called
  182. $this->func_call = "\$db->get_results(\"$query\", $output)";
  183. // If there is a query then perform it if not then use cached results..
  184. if ( $query )
  185. {
  186. $this->query($query);
  187. }
  188. // Send back array of objects. Each row is an object
  189. if ( $output == OBJECT )
  190. {
  191. return $this->last_result;
  192. }
  193. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  194. {
  195. if ( $this->last_result )
  196. {
  197. $i=0;
  198. foreach( $this->last_result as $row )
  199. {
  200. $new_array[$i] = get_object_vars($row);
  201. if ( $output == ARRAY_N )
  202. {
  203. $new_array[$i] = array_values($new_array[$i]);
  204. }
  205. $i++;
  206. }
  207. return $new_array;
  208. }
  209. else
  210. {
  211. return array();
  212. }
  213. }
  214. }
  215. /**********************************************************************
  216. * Function to get column meta data info pertaining to the last query
  217. * see docs for more info and usage
  218. */
  219. function get_col_info($info_type="name",$col_offset=-1)
  220. {
  221. if ( $this->col_info )
  222. {
  223. if ( $col_offset == -1 )
  224. {
  225. $i=0;
  226. foreach($this->col_info as $col )
  227. {
  228. $new_array[$i] = $col->{$info_type};
  229. $i++;
  230. }
  231. return $new_array;
  232. }
  233. else
  234. {
  235. return $this->col_info[$col_offset]->{$info_type};
  236. }
  237. }
  238. }
  239. /**********************************************************************
  240. * store_cache
  241. */
  242. function store_cache($query,$is_insert)
  243. {
  244. // The would be cache file for this query
  245. $cache_file = $this->cache_dir.'/'.md5($query);
  246. // disk caching of queries
  247. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
  248. {
  249. if ( ! is_dir($this->cache_dir) )
  250. {
  251. $this->register_error("Could not open cache dir: $this->cache_dir");
  252. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  253. }
  254. else
  255. {
  256. // Cache all result values
  257. $result_cache = array
  258. (
  259. 'col_info' => $this->col_info,
  260. 'last_result' => $this->last_result,
  261. 'num_rows' => $this->num_rows,
  262. 'return_value' => $this->num_rows,
  263. );
  264. file_put_contents($cache_file, serialize($result_cache));
  265. if( file_exists($cache_file . ".updating") )
  266. unlink($cache_file . ".updating");
  267. }
  268. }
  269. }
  270. /**********************************************************************
  271. * get_cache
  272. */
  273. function get_cache($query)
  274. {
  275. // The would be cache file for this query
  276. $cache_file = $this->cache_dir.'/'.md5($query);
  277. // Try to get previously cached version
  278. if ( $this->use_disk_cache && file_exists($cache_file) )
  279. {
  280. // Only use this cache file if less than 'cache_timeout' (hours)
  281. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) &&
  282. !(file_exists($cache_file . ".updating") && (time() - filemtime($cache_file . ".updating") < 60)) )
  283. {
  284. touch($cache_file . ".updating"); // Show that we in the process of updating the cache
  285. }
  286. else
  287. {
  288. $result_cache = unserialize(file_get_contents($cache_file));
  289. $this->col_info = $result_cache['col_info'];
  290. $this->last_result = $result_cache['last_result'];
  291. $this->num_rows = $result_cache['num_rows'];
  292. $this->from_disk_cache = true;
  293. // If debug ALL queries
  294. $this->trace || $this->debug_all ? $this->debug() : null ;
  295. return $result_cache['return_value'];
  296. }
  297. }
  298. }
  299. /**********************************************************************
  300. * Dumps the contents of any input variable to screen in a nicely
  301. * formatted and easy to understand way - any type: Object, Var or Array
  302. */
  303. function vardump($mixed='')
  304. {
  305. // Start outup buffering
  306. ob_start();
  307. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  308. echo "<pre><font face=arial>";
  309. if ( ! $this->vardump_called )
  310. {
  311. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  312. }
  313. $var_type = gettype ($mixed);
  314. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  315. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  316. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  317. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  318. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  319. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  320. echo "\n<hr size=1 noshade color=dddddd>";
  321. // Stop output buffering and capture debug HTML
  322. $html = ob_get_contents();
  323. ob_end_clean();
  324. // Only echo output if it is turned on
  325. if ( $this->debug_echo_is_on )
  326. {
  327. echo $html;
  328. }
  329. $this->vardump_called = true;
  330. return $html;
  331. }
  332. /**********************************************************************
  333. * Alias for the above function
  334. */
  335. function dumpvar($mixed)
  336. {
  337. $this->vardump($mixed);
  338. }
  339. /**********************************************************************
  340. * Displays the last query string that was sent to the database & a
  341. * table listing results (if there were any).
  342. * (abstracted into a seperate file to save server overhead).
  343. */
  344. function debug($print_to_screen=true)
  345. {
  346. // Start outup buffering
  347. ob_start();
  348. echo "<blockquote>";
  349. // Only show ezSQL credits once..
  350. if ( ! $this->debug_called )
  351. {
  352. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  353. }
  354. if ( $this->last_error )
  355. {
  356. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  357. }
  358. if ( $this->from_disk_cache )
  359. {
  360. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  361. }
  362. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  363. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  364. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  365. echo "<blockquote>";
  366. if ( $this->col_info )
  367. {
  368. // =====================================================
  369. // Results top rows
  370. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  371. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  372. for ( $i=0; $i < count($this->col_info); $i++ )
  373. {
  374. /* when selecting count(*) the maxlengh is not set, size is set instead. */
  375. echo "<td nowrap align=left valign=top><font size=1 color=555599 face=arial>{$this->col_info[$i]->type}";
  376. if (!isset($this->col_info[$i]->max_length))
  377. {
  378. echo "{$this->col_info[$i]->size}";
  379. } else {
  380. echo "{$this->col_info[$i]->max_length}";
  381. }
  382. echo "</font><br><span style='font-family: arial; font-size: 10pt; font-weight: bold;'>{$this->col_info[$i]->name}</span></td>";
  383. }
  384. echo "</tr>";
  385. // ======================================================
  386. // print main results
  387. if ( $this->last_result )
  388. {
  389. $i=0;
  390. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  391. {
  392. $i++;
  393. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  394. foreach ( $one_row as $item )
  395. {
  396. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  397. }
  398. echo "</tr>";
  399. }
  400. } // if last result
  401. else
  402. {
  403. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  404. }
  405. echo "</table>";
  406. } // if col_info
  407. else
  408. {
  409. echo "<font face=arial size=2>No Results</font>";
  410. }
  411. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  412. // Stop output buffering and capture debug HTML
  413. $html = ob_get_contents();
  414. ob_end_clean();
  415. // Only echo output if it is turned on
  416. if ( $this->debug_echo_is_on && $print_to_screen)
  417. {
  418. echo $html;
  419. }
  420. $this->debug_called = true;
  421. return $html;
  422. }
  423. /**********************************************************************
  424. * Naughty little function to ask for some remuniration!
  425. */
  426. function donation()
  427. {
  428. 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>";
  429. }
  430. /**********************************************************************
  431. * Timer related functions
  432. */
  433. function timer_get_cur()
  434. {
  435. list($usec, $sec) = explode(" ",microtime());
  436. return ((float)$usec + (float)$sec);
  437. }
  438. function timer_start($timer_name)
  439. {
  440. $this->timers[$timer_name] = $this->timer_get_cur();
  441. }
  442. function timer_elapsed($timer_name)
  443. {
  444. return round($this->timer_get_cur() - $this->timers[$timer_name],2);
  445. }
  446. function timer_update_global($timer_name)
  447. {
  448. if ( $this->do_profile )
  449. {
  450. $this->profile_times[] = array
  451. (
  452. 'query' => $this->last_query,
  453. 'time' => $this->timer_elapsed($timer_name)
  454. );
  455. }
  456. $this->total_query_time += $this->timer_elapsed($timer_name);
  457. }
  458. /**********************************************************************
  459. * Creates a SET nvp sql string from an associative array (and escapes all values)
  460. *
  461. * Usage:
  462. *
  463. * $db_data = array('login'=>'jv','email'=>'jv@vip.ie', 'user_id' => 1, 'created' => 'NOW()');
  464. *
  465. * $db->query("INSERT INTO users SET ".$db->get_set($db_data));
  466. *
  467. * ...OR...
  468. *
  469. * $db->query("UPDATE users SET ".$db->get_set($db_data)." WHERE user_id = 1");
  470. *
  471. * Output:
  472. *
  473. * login = 'jv', email = 'jv@vip.ie', user_id = 1, created = NOW()
  474. */
  475. function get_set($params)
  476. {
  477. if( !is_array( $params ) )
  478. {
  479. $this->register_error( 'get_set() parameter invalid. Expected array in '.__FILE__.' on line '.__LINE__);
  480. return;
  481. }
  482. $sql = array();
  483. foreach ( $params as $field => $val )
  484. {
  485. if ( $val === 'true' || $val === true )
  486. $val = 1;
  487. if ( $val === 'false' || $val === false )
  488. $val = 0;
  489. switch( $val ){
  490. case 'NOW()' :
  491. case 'NULL' :
  492. $sql[] = "$field = $val";
  493. break;
  494. default :
  495. $sql[] = "$field = '".$this->escape( $val )."'";
  496. }
  497. }
  498. return implode( ', ' , $sql );
  499. }
  500. }