Correcting teacher:查无此人
Correction status:qualified
Teacher's comments:完成的不错,继续加油。
<?php
class Db{
protected $table = null;
public function __construct($dsn,$user,$password,$table){
$this-> pdo = new PDO($dsn,$user,$password);
$this->table =$table;
}
public function create($data){
$sql = "INSERT INTO {$this->table} SET";
if(is_array($data)){
foreach ($data as $k=>$v){
$sql .=$k.'="'. $v.'",';
}
}else{
return false;
}
$sql = rtrim(trim($sql),',').';';
$stmt = $this->pdo->prepare($sql);
}
public function read($where,$order,$limit=10,$fields='*'){
//创建SQL语句
$sql = 'SELECT ';
if (is_array($fields)) {
foreach ($fields as $field) {
$sql .= $field.', ';
}
} else {
$sql .= $fields;
}
$sql = rtrim(trim($sql),',');
$sql .= ' FROM '.$this->table;
//查询条件
if(!empty($where)){
$sql .= ' WHERE '.$where;
}
//排序条件
if(!empty($order)) {
$sql .= ' order by '.$order;
}
//分页条件
if(!empty($limit)) {
$sql .= ' limit '.$limit;
}
$sql .= ';';
//创建PDO预处理对象
$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 update($table,$data=[], $where=''){
$sql = "UPDATE {$this->table} SET ";
//组装修改语句
if(is_array($data)){
foreach ($data as $k=>$v) {
$sql .= $k.'="'.$v.'", ';
}
}
//去掉尾部逗号,并添加分号结束
$sql = rtrim(trim($sql),',');
//查询条件
if(!empty($where)){
$sql .= ' WHERE '.$where;
}
//创建PDO预处理对象
$stmt = $this->pdo->prepare($sql);
//执行新增操作
if($stmt->execute()){
if($stmt->rowCount()>0){
return true;
}
} else {
return false;
}
}
public function delete($table,$where){
$sql = "DELETE FROM {$this->table} ";
//查询条件
if(!empty($where)){
$sql .= ' WHERE '.$where;
}
//创建PDO预处理对象
$stmt = $this->pdo->prepare($sql);
//执行删除操作
if($stmt->execute()){
if($stmt->rowCount()>0){
return true;
}
} else {
return false;
}
}
}
$d = new Db('mysql:host=localhost;dbname=php2020','root','roottt','user');
$d->read('uid=1','age DESC');
print_r($d);