📂 LapTH — File Browser

🏠 Root / Buoi 8 / Db.php
File: Db.php — text/x-php

← Quay lại | ⬇️ Download | ▶️ Chạy file này (Tab mới)

Nội dung code:

<?php

class Db {
    protected $pdo;

    public function __construct() {
        // Try to use central project config
        $projCfg = __DIR__ . '/../../config/config.php';
        if (file_exists($projCfg)) {
            require_once $projCfg;
        }
        try {
            $dsn = 'mysql:host=' . (defined('DB_HOST') ? DB_HOST : 'localhost') . ';dbname=' . (defined('DB_NAME') ? DB_NAME : 'bookstore') . ';charset=utf8mb4';
            $this->pdo = new PDO($dsn, defined('DB_USER') ? DB_USER : 'root', defined('DB_PASS') ? DB_PASS : '');
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->exec("SET NAMES 'utf8'");
        } catch (Exception $e) {
            echo "Lỗi kết nối: " . $e->getMessage();
            exit;
        }
    }

    // Phương thức thực thi câu lệnh SELECT
    public function query($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    // Phương thức thực thi câu lệnh INSERT, UPDATE, DELETE
    public function execute($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->rowCount();
    }
}