Handwritten a pdo database operation class in php (addition, deletion, modification and query examples are attached)

Advantages of database operation classes

It can be said that there are many advantages, and the common advantages are easy maintenance, reuse, high efficiency, security, and easy expansion. For example, PDO supports many types of databases. Unlike mysqli, PDO also supports other databases, and a set of writing methods can match multiple databases, while mysqli only supports mysql.

the code

Db.php

<?php
/**
 * 数据库的基本操作
 */

class Db
{
    // 数据库的默认连接参数
    private $dbConfig=[
        'db'=>'mysql', // 数据库类型
        'host'=>'localhost', // 主机名称
        'port'=>'3306', // 默认端口
        'user'=>'root', // 用户名
        'pass'=>'root', // 密码
        'charset'=>'utf8', // 默认字符集
        'dbname'=>'edu', // 默认数据库
    ];

    // 新增主键id
    public $insertId = null;

    // 受影响的记录
    public $num = 0;

    // 单例模式,本类的实例
    private static $instance = null;

    // 数据库的连接
    private $conn = null;

    /**
     * Db构造方法
     * 私有化以防止外部实例化
     */
    private function __construct($params=[])
    {
        // 初始化连接参数
        $this->dbConfig = array_merge($this->dbConfig,$params);
        // 连接数据库
        $this->connect();
    }

    /**
     * 禁止外部克隆该实例
     */
    private function __clone()
    {
        // TODO:Implement __clone() method.
    }

    /**
     * 获取当前类的单一实例
     */
    public static function getInstance($params=[])
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    private function connect()
    {
        try{
            // 配置数据源DSN
            $dsn = "{$this->dbConfig['db']}:host={$this->dbConfig['host']};port={$this->dbConfig['port']};dbname={$this->dbConfig['dbname']};charset={$this->dbConfig['charset']}";

            // 创建PDO对象
            $this->conn = new PDO($dsn,$this->dbConfig['user'],$this->dbConfig['pass']);
            
            // 设置客户端字符集
            $this->conn->query("SET NAMES {$this->dbConfig['charset']}");

        }catch (PDOException $e){
            die('数据库连接失败'.$e->getMessage());
        }
    }

    /** 
     * 完成数据表的操作:CURD
     */
    
    public function exec($sql)
    {
        $num = $this->conn->exec($sql);
        // 如果有受影响的记录
        if($num > 0){
            // 如果是新增操作,初始化新增主键id属性
            if(null !==$this->conn->lastInsertId()){
                $this->insertId = $this->conn->lastInsertId();
            }
            $this->num = $num; // 返回受影响的记录
        }else{
            $error = $this->conn->errorInfo(); // 获取最后操作错误信息的数组
            var_dump($error);
        }
    }

    // 获取单条查询结果
    public function fetch($sql)
    {
        return $this->conn->query($sql)->fetch(PDO::FETCH_ASSOC);
    }

    // 获取多条查询结果
    public function fetchAll($sql)
    {
        return $this->conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

transfer

Demo.php

<?php
/**
 * Db类测试
 */

require 'Db.php';

// 获取Db类实例
$db = Db::getInstance();

// 新增操作
// $sql = "INSERT student SET name='张一鸣',email='[email protected]',grade='59',course='golang'";
// $db->exec($sql);
// echo '成功插入了'.$db->num.'条记录,主键id是'.$db->insertId;

// 删除操作
// $sql = "DELETE FROM student WHERE id='4'";
// $db->exec($sql);
// echo '成功删除了'.$db->num.'条记录';

// 更新操作
// $sql = "UPDATE student SET grade='1199' WHERE id='1'";
// $db->exec($sql);
// echo '成功更新了'.$db->num.'条记录';

// 查询单条操作
// $sql = "SELECT id,name,email,grade FROM student WHERE grade < '60'";
// $row = $db->fetch($sql);
// var_dump($row);

// // 查询多条操作
// $sql = "SELECT id,name,email,grade FROM student WHERE grade > '80'";
// $rows = $db->fetchAll($sql);
// var_dump($rows);
?>

Database table structure

 

SQL

Select all the following SQL statements and paste them into the SQL execution box of the database management tool for execution to quickly create a test database.

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- 主机: localhost
-- 生成日期: 2022-08-08 10:46:35
-- 服务器版本: 5.7.26
-- PHP 版本: 7.3.4

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- 数据库: `edu`
--

-- --------------------------------------------------------

--
-- 表的结构 `student`
--

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `email` text COLLATE utf8_unicode_ci NOT NULL,
  `grade` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `course` varchar(32) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- 转存表中的数据 `student`
--

INSERT INTO `student` (`id`, `name`, `email`, `grade`, `course`) VALUES
(1, '王兴', '[email protected]', '80', 'ruby'),
(2, '黄峥', '[email protected]', '68', 'mysql'),
(6, '李彦宏', '[email protected]', '95', 'python'),
(5, '马云', '[email protected]', '88', 'php'),
(7, '刘强东', '[email protected]', '76', 'C++'),
(8, '马化腾', '[email protected]', '59', 'java'),
(9, '张一鸣', '[email protected]', '77', 'golang');

--
-- 转储表的索引
--

--
-- 表的索引 `student`
--
ALTER TABLE `student`
  ADD PRIMARY KEY (`id`);

--
-- 在导出的表使用AUTO_INCREMENT
--

--
-- 使用表AUTO_INCREMENT `student`
--
ALTER TABLE `student`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

author

TANKING

Guess you like

Origin blog.csdn.net/weixin_39927850/article/details/127913238