2. 描述PDO的本质与原理是什么? 为什么要用预处理?
PDO本质是一个包含对数据库相关操作的类
PDO原理是创建一个实例对象,然后调用类中的相关方法对选中的数据库进行操作
预处理:可以防止sql注入攻击,可以实现数据延迟绑定
<?php
namespace php_cn;
use PDO;
// 1. 实例演示数据库的CURD操作
// 连接数据库
$dsn = "mysql:host=localhost;dbname=phpedu;port:3306;charset=utf8;";
$db = new PDO($dsn,'root','root');
// 增加
$sql = 'INSERT `staff` SET `name`=?,`gender`=?,`email`=?';
$stmt = $db->prepare($sql);
$stmt->execute(['Dave',0,'Dave@qq.com']);
$stmt->execute(['John',0,'John@qq.com']);
$stmt->execute(['Frank',0,'Frank@qq.com']);
$stmt->execute(['Jane',1,'Jane@qq.com']);
$stmt->execute(['David',0,'David@qq.com']);
$stmt->execute(['Lee',0,'Lee@qq.com']);
$stmt->execute(['Demon',0,'Demon@qq.com']);
$stmt->execute(['Ash',0,'Ash@qq.com']);
$stmt->execute(['Zarah',1,'Zarah@qq.com']);
$stmt->execute(['Sarah',1,'Sarah@qq.com']);
// 删除
$sql = 'DELETE FROM `staff` WHERE `id`=?';
$stmt = $db->prepare($sql);
$stmt->execute([4]);
// 修改
$sql = 'UPDATE `staff` SET `name`=? WHERE `id`=?';
$stmt = $db->prepare($sql);
$stmt->execute(['meimei',5]);
// 查询
$sql = 'SELECT `id`,`name` FROM `staff` WHERE `id`>?';
$stmt = $db->prepare($sql);
$stmt->execute([3]);
$staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($staffs as $staff){
printf("<pre>%s</pre>",print_r($staff,true));
}
// 关闭数据库
$db = null;