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

/php/extlib/ezsql/ezsql_postgres.php

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