Database.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App;
  3. use PDO;
  4. use PDOException;
  5. use Exception;
  6. class Database
  7. {
  8. private static $instance = null;
  9. private $connection;
  10. private function __construct()
  11. {
  12. $dbPath = \Config::PATH['root'] . '/database/database.db';
  13. try {
  14. $this->connection = new PDO('sqlite:' . $dbPath);
  15. $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  16. $this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  17. } catch (PDOException $e) {
  18. throw new Exception('Database connection failed: ' . $e->getMessage());
  19. }
  20. }
  21. public static function getInstance()
  22. {
  23. if (self::$instance === null) {
  24. self::$instance = new self();
  25. }
  26. return self::$instance;
  27. }
  28. public function getConnection()
  29. {
  30. return $this->connection;
  31. }
  32. public function query($sql, $params = [])
  33. {
  34. try {
  35. $stmt = $this->connection->prepare($sql);
  36. $stmt->execute($params);
  37. return $stmt;
  38. } catch (PDOException $e) {
  39. throw new Exception('Query failed: ' . $e->getMessage());
  40. }
  41. }
  42. public function fetchAll($sql, $params = [])
  43. {
  44. $stmt = $this->query($sql, $params);
  45. return $stmt->fetchAll();
  46. }
  47. public function fetchOne($sql, $params = [])
  48. {
  49. $stmt = $this->query($sql, $params);
  50. return $stmt->fetch();
  51. }
  52. public function execute($sql, $params = [])
  53. {
  54. $stmt = $this->query($sql, $params);
  55. return $stmt->rowCount();
  56. }
  57. public function lastInsertId()
  58. {
  59. return $this->connection->lastInsertId();
  60. }
  61. }