pgsql.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. class Db_Pgsql implements IDb {
  3. private $link;
  4. private $last_error;
  5. function connect($host, $user, $pass, $db, $port) {
  6. $string = "dbname=$db user=$user";
  7. if ($pass) {
  8. $string .= " password=$pass";
  9. }
  10. if ($host) {
  11. $string .= " host=$host";
  12. }
  13. if (is_numeric($port) && $port > 0) {
  14. $string = "$string port=" . $port;
  15. }
  16. $this->link = pg_connect($string);
  17. if (!$this->link) {
  18. die("Unable to connect to database (as $user to $host, database $db):" . pg_last_error());
  19. }
  20. $this->init();
  21. return $this->link;
  22. }
  23. function escape_string($s, $strip_tags = true) {
  24. if ($strip_tags) $s = strip_tags($s);
  25. return pg_escape_string($s);
  26. }
  27. function query($query, $die_on_error = true) {
  28. $result = @pg_query($this->link, $query);
  29. if (!$result) {
  30. $this->last_error = @pg_last_error($this->link);
  31. @pg_query($this->link, "ROLLBACK");
  32. $query = htmlspecialchars($query); // just in case
  33. user_error("Query $query failed: " . ($this->link ? $this->last_error : "No connection"),
  34. $die_on_error ? E_USER_ERROR : E_USER_WARNING);
  35. }
  36. return $result;
  37. }
  38. function fetch_assoc($result) {
  39. return pg_fetch_assoc($result);
  40. }
  41. function num_rows($result) {
  42. return pg_num_rows($result);
  43. }
  44. function fetch_result($result, $row, $param) {
  45. return pg_fetch_result($result, $row, $param);
  46. }
  47. function close() {
  48. return pg_close($this->link);
  49. }
  50. function affected_rows($result) {
  51. return pg_affected_rows($result);
  52. }
  53. function last_error() {
  54. return pg_last_error($this->link);
  55. }
  56. function last_query_error() {
  57. return $this->last_error;
  58. }
  59. function init() {
  60. $this->query("set client_encoding = 'UTF-8'");
  61. pg_set_client_encoding("UNICODE");
  62. $this->query("set datestyle = 'ISO, european'");
  63. $this->query("set TIME ZONE 0");
  64. $this->query("set cpu_tuple_cost = 0.5");
  65. return true;
  66. }
  67. }
  68. ?>