PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/server/php/ez_sql/ez_sql_core.php

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