Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
namespace pdo;
//连接数据库
require __DIR__ . '/config/connect.php';
//插入 INSERT 表名 SET 字段1=值1,字段2=值2,...
//?关键字全大写,表名字段名使用`反引号
$sqlInsert = 'INSERT `staff` SET `name`=?,`gender`=?,`email`=?';
//* '?'匿名占位符,':字段名'命名占位符
//* $sqlInsert = 'INSERT `staff` SET `name`=:name,`gender`=:gender,`email`=:email';
//创建SQL语句模板对象
$stmt = $db->prepare($sqlInsert);
$stmt->execute(['张三', '1', 'z3@qq.com']);
$stmt->execute(['李四', '0', 'l4@qq.com']);
$stmt->execute(['王五', '1', 'w5@qq.com']);
$stmt->execute(['赵六', '0', 'z6@qq.com']);
// *若条件来自于外部例如url中的get参数
//* $stmt->execute([':id'=?$_GET['id'],':gender'=?$_GET['gender'],':email'=?$_GET['email']]);
include __DIR__ . '/check.php';
//更新 UPDATE 表名 SET 字段1=值1,字段2=值2,... WHERE 更新条件
$sqlUpdate = 'UPDATE `staff` SET `name`=? WHERE `id`=?';
$stmt = $db->prepare($sqlUpdate);
$stmt->execute(['王三', '3']);
include __DIR__ . '/check.php';
//删除 DELETE FROM 表名 WHERE 删除条件
$sqlUpdate = 'DELETE FROM `staff` WHERE `id`=?';
$stmt = $db->prepare($sqlUpdate);
$stmt->execute(['3']);
include __DIR__ . '/check.php';
//查询 SELECT 字段列表 FROM 表名 WHERE 查询条件
$sqlUpdate = 'SELECT * FROM `staff` WHERE `id`<=?';
$stmt = $db->prepare($sqlUpdate);
$stmt->execute(['10']);
include __DIR__ . '/check.php';
//?单次查询
//FETCH默认会返回关联和索引两部分
//方法一:$stmt->fetch(PDO::FETCH_ASSOC) PDO::FETCH_ASSOC只取关联部分
printf('<pre>%s</pre>', print_r($stmt->fetch(), true));
//extract($stmt->fetch());
//echo "$id,$name,$gender,$email";
//?多条查询
//printf('<pre>%s</pre>', print_r($stmt->fetchAll(), true));
foreach ($stmt->fetchAll() as $key) {
extract($key);
if ($gender === '1') {
$gender = '男';
} else $gender = '女';
echo "$id---$name---$gender---$email<br>";
//printf('<pre>%s</pre>', print_r($key, true));
}
PDO本质是一个包含对数据库相关操作的类
PDO原理是创建一个实例对象,然后调用类中的相关方法对选中的数据库进行操作
预处理:可以防止sql注入攻击,可以实现数据延迟绑定