pdo.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. class Db_PDO implements IDb {
  3. private $pdo;
  4. function connect($host, $user, $pass, $db, $port) {
  5. $connstr = DB_TYPE . ":host=$host;dbname=$db";
  6. if (DB_TYPE == "mysql") $connstr .= ";charset=utf8";
  7. try {
  8. $this->pdo = new PDO($connstr, $user, $pass);
  9. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  10. $this->init();
  11. } catch (PDOException $e) {
  12. die($e->getMessage());
  13. }
  14. return $this->pdo;
  15. }
  16. function escape_string($s, $strip_tags = true) {
  17. if ($strip_tags) $s = strip_tags($s);
  18. $qs = $this->pdo->quote($s);
  19. return mb_substr($qs, 1, mb_strlen($qs)-2);
  20. }
  21. function query($query, $die_on_error = true) {
  22. try {
  23. return new Db_Stmt($this->pdo->query($query));
  24. } catch (PDOException $e) {
  25. user_error($e->getMessage(), $die_on_error ? E_USER_ERROR : E_USER_WARNING);
  26. }
  27. }
  28. function fetch_assoc($result) {
  29. try {
  30. if ($result) {
  31. return $result->fetch();
  32. } else {
  33. return null;
  34. }
  35. } catch (PDOException $e) {
  36. user_error($e->getMessage(), E_USER_WARNING);
  37. }
  38. }
  39. function num_rows($result) {
  40. try {
  41. if ($result) {
  42. return $result->rowCount();
  43. } else {
  44. return false;
  45. }
  46. } catch (PDOException $e) {
  47. user_error($e->getMessage(), E_USER_WARNING);
  48. }
  49. }
  50. function fetch_result($result, $row, $param) {
  51. return $result->fetch_result($row, $param);
  52. }
  53. function close() {
  54. $this->pdo = null;
  55. }
  56. function affected_rows($result) {
  57. try {
  58. if ($result) {
  59. return $result->rowCount();
  60. } else {
  61. return null;
  62. }
  63. } catch (PDOException $e) {
  64. user_error($e->getMessage(), E_USER_WARNING);
  65. }
  66. }
  67. function last_error() {
  68. return join(" ", $this->pdo->errorInfo());
  69. }
  70. function init() {
  71. switch (DB_TYPE) {
  72. case "pgsql":
  73. $this->query("set client_encoding = 'UTF-8'");
  74. $this->query("set datestyle = 'ISO, european'");
  75. $this->query("set TIME ZONE 0");
  76. return;
  77. case "mysql":
  78. $this->query("SET time_zone = '+0:0'");
  79. return;
  80. }
  81. return true;
  82. }
  83. }