把 php公用方法库中的 数据库操作函数, 重写到 Db类中
<?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);
做这个作业时候发现自身很多问题,有很多知识点忘记了,需要重新复习!