PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/jvs13-paginacion-php/libs/ez_sql_core.php

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