Home  >  Article  >  Backend Development  >  How to use PHP's PDO to encapsulate highly operable database classes

How to use PHP's PDO to encapsulate highly operable database classes

PHPz
PHPzOriginal
2024-02-26 12:18:061177browse

How to use PHPs PDO to encapsulate highly operable database classes

How PHP uses PDO to encapsulate simple and easy-to-use DB classes

Introduction:
In PHP development, the database is a very important part. In order to better operate the database, we can use PDO (PHP Data Objects) extension to connect, query and operate the database. This article will introduce how to use PDO to encapsulate a simple and easy-to-use DB class to facilitate developers to perform database operations.

1. Create DB class
First, we create a DB class, which will encapsulate commonly used database operation methods. The code is as follows:

class DB
{
    private $pdo;  // pdo对象

    public function __construct($host, $dbname, $username, $password)
    {
        $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
        $options = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        );
        $this->pdo = new PDO($dsn, $username, $password, $options);
    }

    public function query($sql, $params = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    public function fetchAll($sql, $params = [])
    {
        $stmt = $this->query($sql, $params);
        return $stmt->fetchAll();
    }

    public function fetch($sql, $params = [])
    {
        $stmt = $this->query($sql, $params);
        return $stmt->fetch();
    }

    public function insert($table, $data)
    {
        $columns = implode(', ', array_keys($data));
        $values = ':' . implode(', :', array_keys($data));
        $sql = "INSERT INTO $table ($columns) VALUES ($values)";
        $this->query($sql, $data);
    }

    public function update($table, $data, $where = [])
    {
        $set = '';
        foreach ($data as $key => $value) {
            $set .= "$key = :$key, ";
        }
        $set = rtrim($set, ', ');
        $whereClause = '';
        foreach ($where as $key => $value) {
            $whereClause .= "$key = :$key AND ";
        }
        $whereClause = rtrim($whereClause, ' AND ');
        $sql = "UPDATE $table SET $set WHERE $whereClause";
        $this->query($sql, array_merge($data, $where));
    }

    public function delete($table, $where)
    {
        $whereClause = '';
        foreach ($where as $key => $value) {
            $whereClause .= "$key = :$key AND ";
        }
        $whereClause = rtrim($whereClause, ' AND ');
        $sql = "DELETE FROM $table WHERE $whereClause";
        $this->query($sql, $where);
    }
}

2. Using the DB class
Next, we will demonstrate how to use the DB class just encapsulated to perform database operations. First, we need to create a database instance, and then we can use the instance to perform operations such as query, fetchAll, fetch, insert, update, and delete.

// 创建数据库实例
$db = new DB('localhost', 'mydatabase', 'username', 'password');

// 查询操作
$result = $db->fetchAll("SELECT * FROM users");
foreach ($result as $row) {
    echo $row['name'];
}
echo "<br>";

// 插入操作
$db->insert("users", [
    'name' => 'Tom',
    'age' => 20
]);

// 更新操作
$db->update("users", [
    'age' => 21
], [
    'name' => 'Tom'
]);

// 删除操作
$db->delete("users", [
    'name' => 'Tom'
]);

3. Summary
Through the above encapsulation, we can simplify database operations and make the code more readable and easy to use. The DB class provides encapsulation of commonly used query, insert, update and delete operations, greatly improving development efficiency.

The above is an introduction on how to use PDO to encapsulate a simple and easy-to-use DB class. Hope it helps.

The above is the detailed content of How to use PHP's PDO to encapsulate highly operable database classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn