PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/php/extlib/ezsql/ezsql_pdo_sqlite.php

http://github.com/openmelody/melody
PHP | 543 lines | 305 code | 122 blank | 116 comment | 40 complexity | 44bcaca3ca417bbc35a1f3ea7b8155a3 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0, LGPL-2.1
  1. <?php
  2. // ==================================================================
  3. // Author: Justin Vincent (justin@visunet.ie)
  4. // Web: Http://php.justinvincent.com
  5. // Name: ezSQL
  6. // Desc: Class to make it very easy to deal with SQLite databases.
  7. //
  8. // N.B. ezSQL was converted for use with SQLite
  9. // by Brennan Falkner (fishy5@tampabay.rr.com).
  10. //
  11. // !! IMPORTANT !!
  12. //
  13. // Please send me a mail telling me what you think of ezSQL
  14. // and what your using it for!! Cheers. [ justin@visunet.ie ]
  15. //
  16. // ==================================================================
  17. // User Settings -- CHANGE HERE
  18. define("EZSQL_DB_PATH", $_SERVER['DOCUMENT_ROOT']."/"); // <-- SQLite db path (with trailing slash!!!)
  19. define("EZSQL_DB_NAME", ""); // <-- SQLite db name
  20. // ==================================================================
  21. // ezSQL Constants
  22. define("EZSQL_VERSION","1.26");
  23. define("OBJECT","OBJECT",true);
  24. define("ARRAY_A","ARRAY_A",true);
  25. define("ARRAY_N","ARRAY_N",true);
  26. // ==================================================================
  27. // The Main Class
  28. class ezsql
  29. {
  30. var $debug_called;
  31. var $vardump_called;
  32. var $show_errors = true;
  33. var $num_queries = 0;
  34. var $debug_all = false;
  35. var $last_query;
  36. var $col_info;
  37. // ==================================================================
  38. // DB Constructor - connects to the server and selects a database
  39. function db($dbpath, $dbname)
  40. {
  41. try {
  42. $this->dbh = new PDO('sqlite:' . $dbpath . $dbname);
  43. } catch (Exception $e) {
  44. $this->print_error("Error","<ol><b>Error establishing a database!</b><li>Are you sure you have the correct path?<li>Are you sure that you have typed the correct database instance name?<li>Are you sure that the database is installed?</ol>");
  45. }
  46. }
  47. // ==================================================================
  48. // Select a DB instance (if another one needs to be selected)
  49. function select($dbpath, $dbname)
  50. {
  51. $this->db($dbpath, $dbname);
  52. }
  53. // ====================================================================
  54. // Format a string correctly for safe insert under all PHP conditions
  55. function escape($str)
  56. {
  57. return str_replace("'","''",str_replace("''","'",stripslashes($str)));
  58. }
  59. // ==================================================================
  60. // Print SQL/DB error.
  61. function print_error($title = "SQL/DB Error", $str = "")
  62. {
  63. // All erros go to the global error array $EZSQL_ERROR..
  64. global $EZSQL_ERROR;
  65. // If no error string then you're SOL
  66. if ( !$str )
  67. {
  68. $str = "An error occured, quick go tell someone!";
  69. }
  70. // Log this error to the global array..
  71. $EZSQL_ERROR[] = array
  72. (
  73. "query" => $this->last_query,
  74. "error_str" => $str
  75. );
  76. // Is error output turned on or not..
  77. if ( $this->show_errors )
  78. {
  79. // If there is an error then take note of it
  80. print "<blockquote><font face=arial size=2 color=ff0000>";
  81. print "<b>$title --</b> ";
  82. print "[<font color=000077>$str</font>]";
  83. print "</font></blockquote>";
  84. }
  85. else
  86. {
  87. return false;
  88. }
  89. }
  90. // ==================================================================
  91. // Turn error handling on or off..
  92. function show_errors()
  93. {
  94. $this->show_errors = true;
  95. }
  96. function hide_errors()
  97. {
  98. $this->show_errors = false;
  99. }
  100. // ==================================================================
  101. // Kill cached query results
  102. function flush()
  103. {
  104. // Get rid of these
  105. $this->last_result = null;
  106. $this->col_info = null;
  107. $this->last_query = null;
  108. }
  109. // ==================================================================
  110. // Basic Query - see docs for more detail
  111. function query($query)
  112. {
  113. // For reg expressions
  114. $query = trim($query);
  115. // Flush cached values..
  116. $this->flush();
  117. // Log how the function was called
  118. $this->func_call = "\$db->query(\"$query\")";
  119. // Keep track of the last query for debug..
  120. $this->last_query = $query;
  121. #if(!sqlite_complete($query)){
  122. # $this->print_error("Invalid Query String Format",$query);
  123. # return false;
  124. #}
  125. // Perform the query via std mysql_query function..
  126. $handle = $this->dbh->query($query);
  127. #$this->result = sqlite_fetch_array($handle)?true:false;
  128. $this->result = $handle;
  129. $this->num_queries++;
  130. // If there was an insert, delete or update see how many rows were affected
  131. // (Also, If there there was an insert take note of the insert_id
  132. $query_type = array("insert","delete","update","replace");
  133. // loop through the above array
  134. foreach ( $query_type as $word )
  135. {
  136. // This is true if the query starts with insert, delete or update
  137. if ( preg_match("/^$word\s+/i",$query) )
  138. {
  139. $this->rows_affected = $handle->rowCount();
  140. // This gets the insert ID
  141. if ( $word == "insert" || $word == "replace" )
  142. {
  143. $this->insert_id = $this->dbh->lastInsertId();
  144. // If insert id then return it - true evaluation
  145. return $this->insert_id;
  146. }
  147. // Set to false if there was no insert id
  148. $this->result = false;
  149. }
  150. }
  151. if ( ! $handle )
  152. {
  153. // If there is an error then take note of it..
  154. if ( $php_errormsg )
  155. {
  156. $this->print_error($php_errormsg,$query);
  157. } else {
  158. $this->print_error("Invalid Query",$query);
  159. }
  160. }
  161. else
  162. {
  163. // In other words if this was a select statement..
  164. if ( $this->result )
  165. {
  166. // =======================================================
  167. // Take note of column info
  168. #$i=0;
  169. #foreach(@sqlite_fetch_field_array($handle) as $name)
  170. #{
  171. # $this->col_info[$i++]->name = $name;
  172. #}
  173. // =======================================================
  174. // Store Query Results
  175. $i=0;
  176. while ($row = $handle->fetch(PDO::FETCH_ASSOC)) {
  177. $this->last_result[$i++] = (Object) $row;
  178. }
  179. // Log number of rows the query returned
  180. $this->num_rows = $i;
  181. // If debug ALL queries
  182. $this->debug_all ? $this->debug() : null ;
  183. // If there were results then return true for $db->query
  184. if ( $i )
  185. {
  186. return true;
  187. }
  188. else
  189. {
  190. return false;
  191. }
  192. }
  193. else
  194. {
  195. // If debug ALL queries
  196. $this->debug_all ? $this->debug() : null ;
  197. // Update insert etc. was good..
  198. return true;
  199. }
  200. }
  201. }
  202. // ==================================================================
  203. // Get one variable from the DB - see docs for more detail
  204. function get_var($query=null,$x=0,$y=0)
  205. {
  206. // Log how the function was called
  207. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  208. // If there is a query then perform it if not then use cached results..
  209. if ( $query )
  210. {
  211. $this->query($query);
  212. }
  213. // Extract var out of cached results based x,y vals
  214. if ( $this->last_result[$y] )
  215. {
  216. $values = array_values(get_object_vars($this->last_result[$y]));
  217. }
  218. // If there is a value return it else return null
  219. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  220. }
  221. // ==================================================================
  222. // Get one row from the DB - see docs for more detail
  223. function get_row($query=null,$output=OBJECT,$y=0)
  224. {
  225. // Log how the function was called
  226. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  227. // If there is a query then perform it if not then use cached results..
  228. if ( $query )
  229. {
  230. $this->query($query);
  231. }
  232. // If the output is an object then return object using the row offset..
  233. if ( $output == OBJECT )
  234. {
  235. return $this->last_result[$y]?$this->last_result[$y]:null;
  236. }
  237. // If the output is an associative array then return row as such..
  238. elseif ( $output == ARRAY_A )
  239. {
  240. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  241. }
  242. // If the output is an numerical array then return row as such..
  243. elseif ( $output == ARRAY_N )
  244. {
  245. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  246. }
  247. // If invalid output type was specified..
  248. else
  249. {
  250. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  251. }
  252. }
  253. // ==================================================================
  254. // Function to get 1 column from the cached result set based in X index
  255. // se docs for usage and info
  256. function get_col($query=null,$x=0)
  257. {
  258. // If there is a query then perform it if not then use cached results..
  259. if ( $query )
  260. {
  261. $this->query($query);
  262. }
  263. // Extract the column values
  264. for ( $i=0; $i < count($this->last_result); $i++ )
  265. {
  266. $new_array[$i] = $this->get_var(null,$x,$i);
  267. }
  268. return $new_array;
  269. }
  270. // ==================================================================
  271. // Return the the query as a result set - see docs for more details
  272. function get_results($query=null, $output = OBJECT)
  273. {
  274. // Log how the function was called
  275. $this->func_call = "\$db->get_results(\"$query\", $output)";
  276. // If there is a query then perform it if not then use cached results..
  277. if ( $query )
  278. {
  279. $this->query($query);
  280. }
  281. // Send back array of objects. Each row is an object
  282. if ( $output == OBJECT )
  283. {
  284. return $this->last_result;
  285. }
  286. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  287. {
  288. if ( $this->last_result )
  289. {
  290. $i=0;
  291. foreach( $this->last_result as $row )
  292. {
  293. $new_array[$i] = get_object_vars($row);
  294. if ( $output == ARRAY_N )
  295. {
  296. $new_array[$i] = array_values($new_array[$i]);
  297. }
  298. $i++;
  299. }
  300. return $new_array;
  301. }
  302. else
  303. {
  304. return null;
  305. }
  306. }
  307. }
  308. // ==================================================================
  309. // Function to get column meta data info pertaining to the last query
  310. // see docs for more info and usage
  311. function get_col_info($info_type="name",$col_offset=-1)
  312. {
  313. if ( $this->col_info )
  314. {
  315. if ( $col_offset == -1 )
  316. {
  317. $i=0;
  318. foreach($this->col_info as $col )
  319. {
  320. $new_array[$i] = $col->{$info_type};
  321. $i++;
  322. }
  323. return $new_array;
  324. }
  325. else
  326. {
  327. return $this->col_info[$col_offset]->{$info_type};
  328. }
  329. }
  330. }
  331. // ==================================================================
  332. // Dumps the contents of any input variable to screen in a nicely
  333. // formatted and easy to understand way - any type: Object, Var or Array
  334. function vardump($mixed='')
  335. {
  336. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  337. echo "<pre><font face=arial>";
  338. if ( ! $this->vardump_called )
  339. {
  340. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  341. }
  342. $var_type = gettype ($mixed);
  343. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  344. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  345. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  346. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  347. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  348. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  349. echo "\n<hr size=1 noshade color=dddddd>";
  350. $this->vardump_called = true;
  351. }
  352. // Alias for the above function
  353. function dumpvar($mixed)
  354. {
  355. $this->vardump($mixed);
  356. }
  357. // ==================================================================
  358. // Displays the last query string that was sent to the database & a
  359. // table listing results (if there were any).
  360. // (abstracted into a seperate file to save server overhead).
  361. function debug()
  362. {
  363. echo "<blockquote>";
  364. // Only show ezSQL credits once..
  365. if ( ! $this->debug_called )
  366. {
  367. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  368. }
  369. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  370. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  371. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  372. echo "<blockquote>";
  373. if ( $this->col_info )
  374. {
  375. // =====================================================
  376. // Results top rows
  377. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  378. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  379. for ( $i=0; $i < count($this->col_info); $i++ )
  380. {
  381. 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>";
  382. }
  383. echo "</tr>";
  384. // ======================================================
  385. // print main results
  386. if ( $this->last_result )
  387. {
  388. $i=0;
  389. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  390. {
  391. $i++;
  392. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  393. foreach ( $one_row as $item )
  394. {
  395. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  396. }
  397. echo "</tr>";
  398. }
  399. } // if last result
  400. else
  401. {
  402. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  403. }
  404. echo "</table>";
  405. } // if col_info
  406. else
  407. {
  408. echo "<font face=arial size=2>No Results</font>";
  409. }
  410. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  411. $this->debug_called = true;
  412. }
  413. // =======================================================
  414. // Naughty little function to ask for some remuniration!
  415. function donation()
  416. {
  417. 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>";
  418. }
  419. }
  420. #$db = new db( EZSQL_DB_PATH, EZSQL_DB_NAME );
  421. ?>