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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

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 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

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

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

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.

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

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How to use PHP to develop simple file management functions How to use PHP to develop simple file management functions Sep 20, 2023 pm 01:09 PM

Introduction to how to use PHP to develop simple file management functions: File management functions are an essential part of many web applications. It allows users to upload, download, delete and display files, providing users with a convenient way to manage files. This article will introduce how to use PHP to develop a simple file management function and provide specific code examples. 1. Create a project First, we need to create a basic PHP project. Create the following file in the project directory: index.php: main page, used to display the upload table

See all articles