Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
// 实例演示常用 的CURD操作,特别是各种常用组合,如fetch+while..
namespace pdo_edu;
use PDO;
// 连接
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
//执行添加操作
// CURD: INSERT
$sql = 'INSERT `user` SET `name`= ?,`age`= ?,`email`= ?;';
$res = $db->prepare($sql);
// 引用绑定
$res ->bindParam(1, $name, PDO::PARAM_STR);
$res ->bindParam(2, $age, PDO::PARAM_INT);
$res ->bindParam(3, $email, PDO::PARAM_STR);
// 准备多条数据: 二维数组来模拟
$data = [
['草莓',18,'strawberry@qq.com'],
['菠萝',18,'pineapple@qq.com'],
['芒果',18,'Mango@qq.com'],
['杏',18,'apricot@qq.com'],
['李子',18,'plum@qq.com'],
['西瓜',18,'watermelon@qq.com'],
['木瓜',18,'Papaya@qq.com'],
['哈密瓜',18,'Hami melon@qq.com'],
['山竹',18,'Mangosteen@qq.com'],
['樱桃',18,'Cherry@qq.com'],
];
foreach ($data as list($name, $age, $email)) {
// 执行sql
$stmt->execute();
echo '新增成功, id = ' . $db->lastInsertId() . '<br>';
}
<?php
namespace pdo_edu;
use PDO;
// 连接
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
//执行修改操作
// CURD: UPDATE
$sql = 'UPDATE `user` SET `name`= ?,`age`= ?,`email`= ? where id=?;';
//检查sql是否满足修改条件
if (false === stripos($sql, 'where')) {
exit('无条件下禁止更新,请检查');
}
$res = $db->prepare($sql);
$data = ['杏干','19','xinggan@qq.com',4];
// 执行sql语句
if($res->execute($data)){
if($res->rowCount()>0){
echo '成功的更新'.$res->rowCount().'条记录';
}else{
echo '更新失败';
}
}else{
echo 'sql发生错误';
}
<?php
namespace pdo_edu;
use PDO;
// 连接
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
//执行删除操作
// CURD: DELETE
$sql = 'DELETE FROM `user` where id=?;';
//检查sql是否满足修改条件
if (false === stripos($sql, 'where')) {
exit('无条件下禁止更新,请检查');
}
$res = $db->prepare($sql);
$data = [10];
// 执行sql语句
if($res->execute($data)){
if($res->rowCount()>0){
echo '删除'.$res->rowCount().'条记录';
}else{
echo '删除失败';
}
}else{
echo 'sql发生错误';
}
<?php
namespace pdo_edu;
use PDO;
// 连接
$db = new PDO('mysql:dbname=phpedu', 'root', 'root');
//执行查询操作
// CURD: DELETE
$sql = 'SELECT id,name,age FROM `user` limit ?;';
$res = $db->prepare($sql);
$num = 6;
$res->bindValue(1,$num, PDO::PARAM_INT);
// 执行sql语句
if($res->execute()){
$users = $res->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user){
echo "<pre>";
var_dump($user);
echo "</pre>";
}
}else{
echo 'sql发生错误';
var_dump($res->errorInfo());
}