| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <?php
- namespace App;
- use PDO;
- use PDOException;
- use Exception;
- class Database
- {
- private static $instance = null;
- private $connection;
- private function __construct()
- {
- $dbPath = \Config::PATH['root'] . '/database/database.db';
- try {
- $this->connection = new PDO('sqlite:' . $dbPath);
- $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
- } catch (PDOException $e) {
- throw new Exception('Database connection failed: ' . $e->getMessage());
- }
- }
- public static function getInstance()
- {
- if (self::$instance === null) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- public function getConnection()
- {
- return $this->connection;
- }
- public function query($sql, $params = [])
- {
- try {
- $stmt = $this->connection->prepare($sql);
- $stmt->execute($params);
- return $stmt;
- } catch (PDOException $e) {
- throw new Exception('Query failed: ' . $e->getMessage());
- }
- }
- public function fetchAll($sql, $params = [])
- {
- $stmt = $this->query($sql, $params);
- return $stmt->fetchAll();
- }
- public function fetchOne($sql, $params = [])
- {
- $stmt = $this->query($sql, $params);
- return $stmt->fetch();
- }
- public function execute($sql, $params = [])
- {
- $stmt = $this->query($sql, $params);
- return $stmt->rowCount();
- }
- public function lastInsertId()
- {
- return $this->connection->lastInsertId();
- }
- }
|