PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/shared/ez_sql_core_202console.php

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