自己搞了一天DB类 修改了一些东西 终于成功了 大家来看看如何 讨论讨论
<?php
class Db {
//数据库的连接对象
protected $pdo = null;
// 数据表名
// protected $table;
// 构造方法: 连接数据库,并设置默认数据表名称
public function __construct($dsn, $user, $password){
$this->pdo = new \PDO($dsn, $user, $password);
// $this->table = $table;
}
// 读取
public function read($table,$where='', $fields='*'){
$sql = 'SELECT ';
if ($fields == '*'){
$sql .= '* FROM ';
}else{
$sql .= $fields . ' FRPM ';
}
if ($table){
$sql .= $table;
}
$sql .= $this->table;
if (!$where == ''){
$sql .= ' WHERE '.$where;
}
print_r($sql);
echo '<br>';
$stmt = $this->pdo->prepare($sql);
if($stmt->execute()){
if($stmt->rowCount()>0){
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//返回一个二维数组
return $stmt->fetchAll();
}
} else {
return false;
}
}
// 新增, 参数是数组: 新记录的键值对
public function create($table,$data){
// 字段列表
$fields = ' (name,alias)';
// 值列表
$values = '(:name,:alias)';
// 创建SQL语句
$sql = 'INSERT INTO '.$table.$this->table.$fields.' VALUES '.$values;
print_r( $sql);
// 预处理执行新增操作
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
// 返回新增数量, 新增记录的ID组成的数组
return [
'count'=>$stmt->rowCount(),
'id'=>$this->pdo->lastInsertId()
];
}
// 更新, 为了数据安全, 不允许无条件更新
public function update($table,$data, $where){
// 难点在于SET 参数的处理上,利用传入的$data数组,进行拆装
// 获取数组的键名组成的数组
$keyArr = array_keys($data);
$set = '';
// 遍历键名表示的字段列表,拼装预处理需要的sql语句,注意占符符的表示
foreach ($keyArr as $value) {
$set .= $value . ' = :' .$value. ', ';
// print_r($set);
}
// 去掉最后一个逗号, 注意每个逗号后有一个空格,去除时也要带上这个空格
$set = rtrim($set,', ');
// 预处理执行更新操作
$sql = 'UPDATE '.$table.' SET '.$set .' WHERE ' .$where;
print_r($sql);
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
// 返回被更新的记录数量
return $stmt->rowCount();
}
// 删除: 与更新一样, 这也是危险的写操作, 不允许无条件删除
public function delete($table,$where){
// 预处理执行删除操作
$sql = 'DELETE FROM '.$table.' WHERE '.$where;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->rowCount();
}
}
$dsn = 'mysql:host=localhost;dbname=cms';
$user = 'root';
$password = 'root';
$db = new Db($dsn, $user, $password);
//$a = $db->read('category');
//print_r($a);
// 新增数据
$data = [
'name'=>'kh',
'alias'=>'科幻电影'
];
//$res = $db->create('category',$data);
//echo '成功新增'.$res['count'].'条记录,最新记录的主键ID是: '.$res['id'];
// 更新记录
$data = [
'alias'=>'搞怪电影',
'name'=>'gg',
];
$where = 'cate_id = 6';
//echo '成功更新了: ' .$db->update('category',$data, $where). ' 条记录';
// 删除记录
$where = 'cate_id = 9';
//echo '成功删除了: ' .$db->delete('category',$where). ' 条记录';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号