Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
namespace pdo_edu;
return [
// dsn信息
'type'=>'mysql',
'host'=>'127.0.0.1',
'dbname'=>'phpedu',
'port'=>'3306',
'charset'=>'utf8',
'username'=>'root',
'password'=>'root',
];
<?php
namespace pdo_edu;
use PDO;
$dbConfig = require 'database.php';
extract($dbConfig);//将$dbConfig里面的key和value转换为变量和值
// 1.dsn
$tpl='%s:host=%s;dbname=%s;port=%s;charset=%s';//输出模板
$args = [$type,$host,$dbname,$port,$charset];
$dsn = sprintf($tpl,...$args);//返回输出模板+数组一一对应的字符串
// 2.创建数据对象
$db = new PDO($dsn,$username,$password);
// 设置结果机的默认获取方式:只要关联部分
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
<?php
namespace pdo_edu;
use PDO;
// 链接数据库
require __DIR__ . 'config/connect.php';
<?php
namespace pdo_edu;
use PDO;
// 链接数据库
// echo __DIR__;
require __DIR__ . '/config/connect.php';
// INSERT操作
// INSERT 表名 SET 字段1=值1, 字段2=值2, ....
// 预处理模板
$sql = 'INSERT `people` SET `name`=?,`gender`=?,`email`=?';
// 创建SQL语句模板对象
$stmt = $db->prepare($sql);
// 执行SQL语句
$stmt->execute(['aaa',1,'aaaa@qq.com']);
$stmt->execute(['bbb',1,'aaaa@qq.com']);
$stmt->execute(['ccc',1,'aaaa@qq.com']);
$stmt->execute(['ddd',1,'aaaa@qq.com']);
$stmt->execute(['eee',1,'aaaa@qq.com']);
$stmt->execute(['fff',1,'aaaa@qq.com']);
$stmt->execute(['ggg',1,'aaaa@qq.com']);
$stmt->execute(['hhh',1,'aaaa@qq.com']);
$stmt->execute(['iii',1,'aaaa@qq.com']);
$stmt->execute(['jjj',1,'aaaa@qq.com']);
// 校验是否添加成功
// $stmt->rowCount(): 返回受影响的记录数量
if($stmt->rowCount()>0){
echo'新增成功,新增记录的主键ID为:'.$db->lastInsertId();
}else{
echo'新增失败';
print_r($stmt->errorInfo());
}
// UPDATE操作
$sql1='UPDATE `people` SET `gender` = ? WHERE `id`=?';
$stmt = $db->prepare($sql1);
$stmt->execute([0,21]);
if ($stmt->rowCount()>0){
echo '更新成功';
}else{
echo '更新失败';
print_r($stmt->errorInfo());
}
$sql1 = 'DELETE FROM `people` WHERE `id`=?';
$stmt=$db->prepare($sql1);
$stmt->execute([30]);
if ($stmt->rowCount() > 0) {
echo ' 删除成功';
} else {
echo '删除失败';
print_r($stmt->errorInfo());
}
// SELECT单条查询
$sql = 'SELECT `id`,`name` FROM `people` WHERE `id` > ?';
$stmt = $db->prepare($sql);
$stmt->execute([25]);
// PDO::FETCH_ASSOC: 结果集获取模式,只返回关联部分
while ($staff = $stmt->fetch()) {
printf('<pre>%s</pre>', print_r($staff, true));
}
$sql = 'SELECT `id`,`name` FROM `people` WHERE `id` > ?';
$stmt = $db->prepare($sql);
$stmt->execute([10]);
// fetchAll: 返回全部满足条件的记录集合,二维数组
$staffs = $stmt->fetchAll();
// print_r($staffs);
foreach ($staffs as $staff) {
printf('<pre>%s</pre>', print_r($staff, true));
}
PDO(PHP Data Objects)是一种在PHP里连接数据库的使用接口。PDO与mysqli曾经被建议用来取代原本PHP在用的mysql相关函数,基于数据库使用的安全性,因为后者欠缺对于SQL注入的防护。