PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/ez_sql.pgsql.php

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