批改状态:合格
老师批语:这个案例非常的实用, 完全 可以用在你自己的项目中
我们要实现增删改查的数据库原列表如下:

<?php
namespace _2019C;
// 定义一个接口iJie, 实现数据库操作
interface iJie
{
public function create($data); // 增加数据
public function read(); // 读取数据
public function update($data, $where); // 更新数据
public function delete($where); // 删除数据
}
// 创建类 Db
class Db implements iJie
{
// 数据库的连接对象,给一个空值防止出错
protected $pdo = null;
protected $table;
// 构造方法: 连接数据库,并设置默认的数据表
public function __construct($dsn, $username, $password, $table)
{
$this->pdo = new \PDO($dsn, $username, $password);
$this->table = $table;
}
// 增加数据
public function create($data)
{
// 字段列表,表中有name, age, sex, mobile 字段
$fields = ' (name, age, sex, mobile) ';
$values = ' (:name, :age, :sex, :mobile) ';
// 创建数据库SQL语句
$sql = 'INSERT INTO '.$this->table . $fields . ' VALUES ' . $values;
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
return [
'count' => $stmt->rowCount(),
'id' => $this->pdo->lastInsertId()
];
}
// 读取数据 ,查询操作
public function read($fileds = '*' , $where='', $limit = '0, 5')
{
$where = empty($where) ? '' : ' WHERE ' . $where;
$limit = ' LIMIT ' . $limit;
$sql = 'SELECT '. $fileds . ' FROM ' . $this->table. $where . $limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
// 用二维数组返回所有数据
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
// 更新数据
public function update($data, $where)
{
// 设置SET参数
$keyArr = array_keys($data);
$set = '';
// 遍历数据库字段列表,
foreach ($keyArr as $value) {
$set .= $value . '= :' . $value. ',';
}
//把最后一个逗号删除,
$set =rtrim($set, ', ');
$sql = 'UPDATE '. $this->table.' SET '.$set.' WHERE '.$where;
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
// 返回更新的数量
return $stmt->rowCount();
}
// 删除数据
public function delete($where)
{
$sql = 'DELETE FROM '. $this->table. ' WHERE '.$where;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->rowCount();
}
}
// 实例化Db
$dsn = 'mysql:host=127.0.0.1;dbname=php';
$username = 'root';
$password = 'root';
$table = 'stud';
$db = new Db($dsn, $username, $password, $table);
// 新增操作
$data = [
'name'=> '狗子',
'age'=> 30,
'sex' => 1,
'mobile'=> '13888888888'
];
echo '<hr>';
foreach ($db->read() as $item) {
print_r($item); echo '<br>';
}
echo '<hr>';
// 查询操作
foreach ($db->read('stud_id, name, age', 'age > 18') as $item) {
print_r($item); echo '<br>';
}
// 更新操作
$data = [
'name'=> '狗子',
'age'=> 88,
'sex' => 1,
'mobile'=> '13000000000'
];
$where = 'stud_id = 16';
echo '成功的更新了: ' . $db->update($data, $where) . ' 条记录';
echo '<hr>';
// 删除操作,这里就不执行了
//$where = 'stud_id = 16';
//echo '成功的删除了: ' . $db->delete($where) . ' 条记录';
删除操作也是如此,下面是更新成功后的数据库截图:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号