Correcting teacher:查无此人
Correction status:qualified
Teacher's comments:完成的不错。尽量多用单引号,少用双引号
<?php
class Db{
public $table = null;
public function __construct($dsn,$user,$password,$table) {
$this->pdo = new PDO($dsn,$user,$password);
$this->table = $table;
}
public function create($data) {
//创建SQL语句
$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),',').';';
//创建PDO预处理对象
$stmt = $this->pdo->prepare($sql);
//执行新增操作
if($stmt->execute()){
if($stmt->rowCount()>0){
return true;
}
} else {
return false;
}
}
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=mysite','root','root','movies');
$d->read('mov_id=1','cate_id DESC');
print_r($d);