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

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

Feb 26, 2024 pm 12:18 PM
encapsulation Simple db class

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);
    }
}
Copy after login

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'
]);
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
The easiest way to query the hard drive serial number The easiest way to query the hard drive serial number Feb 26, 2024 pm 02:24 PM

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to write a simple student performance report generator using Java? How to write a simple student performance report generator using Java? Nov 03, 2023 pm 02:57 PM

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

How to write a simple online reservation system through PHP How to write a simple online reservation system through PHP Sep 26, 2023 pm 09:55 PM

How to write a simple online reservation system through PHP. With the popularity of the Internet and users' pursuit of convenience, online reservation systems are becoming more and more popular. Whether it is a restaurant, hospital, beauty salon or other service industry, a simple online reservation system can improve efficiency and provide users with a better service experience. This article will introduce how to use PHP to write a simple online reservation system and provide specific code examples. Create database and tables First, we need to create a database to store reservation information. In MyS

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

MySQL Table Design Guide: Create a Simple Employee Attendance Sheet MySQL Table Design Guide: Create a Simple Employee Attendance Sheet Jul 01, 2023 pm 01:54 PM

MySQL Table Design Guide: Creating a Simple Employee Attendance Table In enterprise management, employee attendance management is a crucial task. In order to accurately record and count employee attendance, we can use the MySQL database to create a simple employee attendance sheet. This article will guide you how to design and create this table, and provide corresponding code examples. First, we need to identify the required fields for the employee attendance sheet. Generally speaking, employee attendance sheets need to contain at least the following fields: employee ID, date, working time, off-duty time

How to write a simple minesweeper game in C++? How to write a simple minesweeper game in C++? Nov 02, 2023 am 11:24 AM

How to write a simple minesweeper game in C++? Minesweeper is a classic puzzle game that requires players to reveal all the blocks according to the known layout of the minefield without stepping on the mines. In this article, we will introduce how to write a simple minesweeper game using C++. First, we need to define a two-dimensional array to represent the map of the Minesweeper game. Each element in the array can be a structure used to store the status of the block, such as whether it is revealed, whether there are mines, etc. In addition, we also need to define

How to write a simple music recommendation system in C++? How to write a simple music recommendation system in C++? Nov 03, 2023 pm 06:45 PM

How to write a simple music recommendation system in C++? Introduction: Music recommendation system is a research hotspot in modern information technology. It can recommend songs to users based on their music preferences and behavioral habits. This article will introduce how to use C++ to write a simple music recommendation system. 1. Collect user data First, we need to collect user music preference data. Users' preferences for different types of music can be obtained through online surveys, questionnaires, etc. Save data in a text file or database

Quick Start: Use Go language functions to implement a simple library management system Quick Start: Use Go language functions to implement a simple library management system Jul 30, 2023 am 09:18 AM

Quick Start: Implementing a Simple Library Management System Using Go Language Functions Introduction: With the continuous development of the field of computer science, the needs of software applications are becoming more and more diverse. As a common management tool, the library management system has also become one of the necessary systems for many libraries, schools and enterprises. In this article, we will use Go language functions to implement a simple library management system. Through this example, readers can learn the basic usage of functions in Go language and how to build a practical program. 1. Design ideas: Let’s first

See all articles