Advantages of database operation classes
The advantages can be said to be very many. The common advantages are easy to maintain, reuse, efficient, safe, and easy to expand. For example, PDO supports a lot of database types. The difference from mysqli is that PDO also supports other databases, and a set of writing methods to match multiple databases, while mysqli only supports mysql.
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='ByteDance@qq.com',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 SQL statements below 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, '王兴', 'meituan@qq.com', '80', 'ruby'),
(2, '黄峥', 'pdd@qq.com', '68', 'mysql'),
(6, '李彦宏', 'baidu@qq.com', '95', 'python'),
(5, '马云', 'mayun@qq.com', '88', 'php'),
(7, '刘强东', 'jd@qq.com', '76', 'C++'),
(8, '马化腾', '10001@qq.com', '59', 'java'),
(9, '张一鸣', 'ByteDance@qq.com', '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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。