Correcting teacher:查无此人
Correction status:qualified
Teacher's comments:完成的不错,继续加油。
<?php
class NB{
function __construct($a,$b,$c,$table)
{
//pdo连接数据库
$this->pdo = new PDO($a,$b,$c);
//需要增删查改的表明
$this->table = $table;
}
//查询
function select($where = '', $limit = 6){
$where = empty($where) ? '' : ' WHERE '.$where;
$limit = ' LIMIT ' . $limit;
$sql = 'SELECT * FROM ' .$this->table. $where . $limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//新增
function insert($data){
//数据表字段列表
$a = '(name,tel,password) ';
//字段值列表
$b = '(:name,:tel,:password)';
//创建sql语句模板
$sql = 'INSERT INTO ' . $this->table . $a .' VALUES' .$b;
//预处理新增操作
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
//返回新增数量,及其主键id
return [
'count' => $stmt->rowCount(),
'id' => $this->pdo->lastInsertId()
];
}
//更新
function update($upda,$upid){
//通过外部数组索引数组
$keyArr = array_keys($upda);
$set = '';
//循环外部索引数组,获得如name=:name
foreach($keyArr as $vv){
// .=能让 $set 获取所有数组,若只有 = ,则只能获取只有一个数组
$set .= $vv . '=:'.$vv . ', ';
}
$set = rtrim($set, ', ');
echo $set;
$sql = 'UPDATE '.$this->table.' SET '.$set.' WHERE ' .$upid;
$stmt = $this->pdo->prepare($sql);
$stmt->execute($upda);
return $stmt->rowCount();
}
//删除
function delete($deid){
$sql = 'DELECT FROM '.$this->table.' WHERE '. $deid;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->rowCount();
}
}
$db = new NB('mysql:host=localhost;dbname=film', 'root', 'root', 'user');
echo print_r($db->pdo);
echo '<hr>';
//查询结果
foreach($db->select() as $v){
print_r($v);
}
echo '<hr>';
//新增
$data = [
'name'=> '轩轩宝贝',
'tel'=>211899,
'password'=>sha1(123456)
];
$inss = $db->insert($data);
echo '成功新增'.$inss['count'].',它的主键id:'. $inss['id'];
echo '<hr>';
//更新
$upda = [
'name' => '轩轩宝贝',
'tel'=> 15566554466
];
$upid = 'id=14';
echo '成功更新了' . $db->update($upda,$upid).'条信息';
echo '<hr>';
//删除
$deid = 'id=12';
echo '成功删除:' .$db->delete($deid). '条信息';