Home > Backend Development > PHP Problem > How to encapsulate database addition, deletion and modification classes in PHP

How to encapsulate database addition, deletion and modification classes in PHP

PHPz
Release: 2023-03-22 15:46:02
Original
1485 people have browsed it

With the development of web applications, the demand for database management is also getting higher and higher. As a PHP programmer, how to optimize the operations of adding, deleting, modifying and checking is a problem that must be solved. This problem can be solved through PHP classes that encapsulate database additions, deletions, and modifications.

1. Why do you need to encapsulate database classes?

Normally, when performing database operations, we will operate in the main logic of the application, such as operating the database in the controller. But in fact, there are several obvious problems with this approach:

  • Code redundancy: In our application, it is likely that multiple controllers need to operate on the database. If each controller writes code for database operations separately, there will be a lot of redundant code.

  • Poor code readability: In this case, the readability of the code is also poor. It is very likely that the same piece of code will appear in multiple controllers, which will cause trouble to other developers.

  • Security issues: There are certain security risks when writing database operation code directly in the application. For example, issues such as sql injection.

To sum up, it is necessary for us to encapsulate our database operation code and make them an independent module. This module needs to have the following characteristics:

  • Have good readability

  • Be able to easily reuse code

  • Has good scalability

  • Can effectively solve security problems

2. Encapsulate the database The basic idea of ​​adding, deleting and modifying classes

In response to the problems mentioned above, we can write classes in the form of php libraries to achieve reuse of classes. The basic idea of ​​encapsulating database addition, deletion and modification classes is as follows:

  • Encapsulate all database operations in a class, such as called db class.

  • Write a general method to implement database addition, deletion, modification and query operations.

  • Implement parameterized queries in methods to effectively avoid security issues such as SQL injection.

  • Capture all error information, encapsulate it into a unified exception and throw it to the upper layer code.

The following is a simple implementation of the db class:

class db {
  private $db_host;
  private $db_user;
  private $db_pass;
  private $db_name;
  private $conn;
  function __construct($db_host, $db_user, $db_pass, $db_name) {
    $this->db_host = $db_host;
    $this->db_user = $db_user;
    $this->db_pass = $db_pass;
    $this->db_name = $db_name;
  }
  // 数据库连接方法
  function connect() {
    $this->conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
    if (!$this->conn) {
      throw new Exception('数据库连接失败');
    }
    mysqli_query($this->conn, "SET NAMES 'utf8'");
  }
  // 数据库关闭方法
  function close() {
    mysqli_close($this->conn);
  }
  // 查询方法,参数化查询
  function query($sql, $params) {
    $stmt = mysqli_prepare($this->conn, $sql);
    if (!$stmt) {
      throw new Exception('query error: '.mysqli_error($this->conn));
    }
    if (count($params) > 0) {
      call_user_func_array('mysqli_stmt_bind_param', array_merge(array($stmt, str_repeat('s', count($params))), $params));
    }
    $result = mysqli_stmt_execute($stmt);
    if (!$result) {
      throw new Exception('query error: '.mysqli_stmt_error($stmt));
    }
    $rows = array();
    $meta = mysqli_stmt_result_metadata($stmt);
    if ($meta) {
      while ($field = mysqli_fetch_field($meta)) {
        $params[] = &$row[$field->name];
      }
      call_user_func_array(array($stmt, 'bind_result'), $params);
      while (mysqli_stmt_fetch($stmt)) {
        $rows[] = $row;
      }
    }
    mysqli_stmt_close($stmt);
    return $rows;
  }
  // 增加方法,参数化查询
  function insert($table, $data) {
    $sql = 'INSERT INTO '.$table.' ('.implode(',', array_keys($data)).') VALUES ('.implode(',', array_fill(0, count($data), '?')).')';
    $result = $this->query($sql, array_values($data));
    return mysqli_affected_rows($this->conn);
  }
  // 更新方法
  function update() {
    // 实现更新方法
  }
  // 删除方法
  function delete() {
    // 实现删除方法
  }
}
Copy after login

3. Use the encapsulated class

When we When you need to add, delete, modify, and query the database, you only need to introduce the db class and then instantiate it. For example:

require_once 'db.php';
$db = new db('localhost', 'root', 'root', 'test');
$db->connect();
$sql = 'INSERT INTO `user`(`name`, `age`) VALUES (?, ?)';
$data = array('Tom', '18');
$db->query($sql, $data);
$db->close();
Copy after login

4. Summary

The class that encapsulates the addition, deletion and modification of the database is a task that we must complete in the web application. By encapsulating database operations into a class, the readability, maintainability and security of the code can be improved, and code reuse can also be facilitated. To sum up, we should pay attention to the development of encapsulated database operation classes.

The above is the detailed content of How to encapsulate database addition, deletion and modification classes in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template