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. print("Unable to connect to database (as $user to $host, database $db):" . pg_last_error());
  19. exit(102);
  20. }
  21. $this->init();
  22. return $this->link;
  23. }
  24. function escape_string($s, $strip_tags = true) {
  25. if ($strip_tags) $s = strip_tags($s);
  26. return pg_escape_string($s);
  27. }
  28. function query($query, $die_on_error = true) {
  29. $result = @pg_query($this->link, $query);
  30. if (!$result) {
  31. $this->last_error = @pg_last_error($this->link);
  32. @pg_query($this->link, "ROLLBACK");
  33. $query = htmlspecialchars($query); // just in case
  34. user_error("Query $query failed: " . ($this->link ? $this->last_error : "No connection"),
  35. $die_on_error ? E_USER_ERROR : E_USER_WARNING);
  36. }
  37. return $result;
  38. }
  39. function fetch_assoc($result) {
  40. return pg_fetch_assoc($result);
  41. }
  42. function num_rows($result) {
  43. return pg_num_rows($result);
  44. }
  45. function fetch_result($result, $row, $param) {
  46. return pg_fetch_result($result, $row, $param);
  47. }
  48. function close() {
  49. return pg_close($this->link);
  50. }
  51. function affected_rows($result) {
  52. return pg_affected_rows($result);
  53. }
  54. function last_error() {
  55. return pg_last_error($this->link);
  56. }
  57. function last_query_error() {
  58. return $this->last_error;
  59. }
  60. function init() {
  61. $this->query("set client_encoding = 'UTF-8'");
  62. pg_set_client_encoding("UNICODE");
  63. $this->query("set datestyle = 'ISO, european'");
  64. $this->query("set TIME ZONE 0");
  65. $this->query("set cpu_tuple_cost = 0.5");
  66. return true;
  67. }
  68. }