db.class.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. class db
  3. {
  4. private static $dbh;
  5. private static $error;
  6. private static $qError;
  7. private static $stmt;
  8. private static function connexion()
  9. {
  10. $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
  11. $options = array(
  12. PDO::ATTR_PERSISTENT => true,
  13. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  14. );
  15. try {
  16. self::$dbh = new PDO($dsn, DB_USER, DB_PASS, $options);
  17. } catch (PDOException $e) {
  18. self::$error = $e->getMessage();
  19. }
  20. }
  21. public static function query(string $query)
  22. {
  23. self::connexion();
  24. self::$stmt = self::$dbh->prepare($query);
  25. }
  26. public static function bind(string $param, string $value = NULL, string $type = null)
  27. {
  28. if (is_null($type)) {
  29. switch (true) {
  30. case is_int($value):
  31. $type = PDO::PARAM_INT;
  32. break;
  33. case is_bool($value):
  34. $type = PDO::PARAM_BOOL;
  35. break;
  36. case is_null($value):
  37. $type = PDO::PARAM_NULL;
  38. break;
  39. default:
  40. $type = PDO::PARAM_STR;
  41. }
  42. }
  43. self::$stmt->bindValue($param, $value, $type);
  44. }
  45. public static function execute()
  46. {
  47. if(core::isDebug()){
  48. ob_start();
  49. $return = self::$stmt->execute();
  50. self::$stmt->debugDumpParams();
  51. $debugOutput = ob_get_clean();
  52. debug::logSession($debugOutput);
  53. return $return;
  54. } else {
  55. return self::$stmt->execute();
  56. }
  57. }
  58. public static function resultset()
  59. {
  60. self::execute();
  61. return self::$stmt->fetchAll(PDO::FETCH_ASSOC);
  62. }
  63. public static function single()
  64. {
  65. self::execute();
  66. return self::$stmt->fetch(PDO::FETCH_ASSOC);
  67. }
  68. public static function rowCount()
  69. {
  70. return self::$stmt->rowCount();
  71. }
  72. public static function lastInsertId()
  73. {
  74. return self::$dbh->lastInsertId();
  75. }
  76. public static function beginTransaction()
  77. {
  78. return self::$dbh->beginTransaction();
  79. }
  80. public static function endTransaction()
  81. {
  82. return self::$dbh->commit();
  83. }
  84. public static function cancelTransaction()
  85. {
  86. return self::$dbh->rollBack();
  87. }
  88. public static function debugDumpParams()
  89. {
  90. return self::$stmt->debugDumpParams();
  91. }
  92. public static function queryError()
  93. {
  94. self::$qError = self::$dbh->errorInfo();
  95. if (!is_null(self::$qError[2])) {
  96. echo self::$qError[2];
  97. }
  98. }
  99. }