<?php
//接口
interface iCurd
{
//增加
public function insert($data);
//删除
public function delete($where);
//设置
public function update($data,$where);
//查询
public function select();
}
class Db implements iCurd
{
//连接数据库对象
protected $pdo;
//数据库表名
protected $table;
//构造方法
public function __construct($dsn,$user,$password,$table = 'staff')
{
//创建pdo连接对象
$this->pdo = new PDO($dsn,$user,$password);
$this->table = $table;
}
//读取操作方法
public function select($field = '*',$where = '',$limit = '1,5')
{
//设置查询条件
$where = empty($where) ? '' : ' WHERE '.$where;
//设置显示
$limit = ' LIMIT '.$limit;
//创建SQL预处理
$sql = 'SELECT '.$field. ' FROM '.$this->table.$where.$limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
//用fetchAll获取数据库数据,并return返回
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//新增操作方法
public function insert($data)
{
//SQL新增语句
//INSERT INTO `表名` (字段列表)VALUE (值列表)
//字段列表
$fields = ' (name,age,sex,position,mobile,hiredate)';
//值列表
$values = ' (:name,:age,:sex,:position,:mobile,:hiredate)';
//创建SQL预处理
$sql = 'INSERT INTO '.$this->table.$fields.' VALUE '.$values;
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
//返回新增数量,新增记录的id组成的数据
return [
'count'=>$stmt->rowCount(),
'id'=>$this->pdo->lastInsertId()
];
}
//更新,为了数据安全,不允许无条件更新
public function update($data, $where)
{
$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';
$name = 'root';
$password = 'root';
$db = new Db($dsn,$name,$password);
foreach ($db->select() as $item) {
print_r($item);
echo '<br>';
}
echo '<hr>';
//设置查询条件
foreach ($db->select('staff_id, name, position','age > 30')as $item) {
print_r($item);
echo '<br>';
}
echo'<hr>';
$data = [
'name'=>'杨洋',
'age'=>20,
'sex'=>1,
'position'=>'电竞高手',
'mobile'=>'13349195254',
'hiredate'=>time()
];
//$res = $db->insert($data);
//echo '成功新增'.$res['count'].'条记录,最新记录的主键ID是: '.$res['id'];
//echo '<hr>';
$data = [
'name' => '江疏影'
];
$where = 'staff_id = 12';
echo '成功更新了:'. $db->update($data,$where).' 条记录';
echo '<hr>';
$where = 'staff_id = 11';
echo '成功删除了:'.$db->delete($where).' 条记录';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号