Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:是不是觉得pdo其实挺简单的
<?php
namespace edu;
use Exception;
use PDO;
$conf = require 'conf.php';
$type = $conf['type'];
$host = $conf['host'];
$dbname = $conf['dbname'];
$username = $conf['username'];
$password = $conf['password'];
$dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
try {
$db = new PDO($dsn, $username, $password);
} catch (Exception $e) {
echo '错误原因: ' . $e->getMessage();
}
?>
<?php
namespace edu;
use PDO;
//连接数据库
require 'common/db.php';
//查询语句
//$sql = 'select * from users';
//$stmt = $db->prepare($sql);
//$stmt->execute();
//foreach($stmt as $val){
// $date = date('Y年m月d日', $val['add_time']);
// printf('ID=%s;Name=%s;Email=%s;Add_time=%s',$val['id'],$val['name'],$val['email'],$date);
//}
//插入语句
//$sql = "INSERT `users` SET `name`= ? , `email`=?,`add_time`=?";
//$stmt = $db->prepare($sql);
//$date = time();
//$data = ['qqq', '2343@qq.com', $date];
//$stmt->execute($data);
//if ($stmt->rowCount() === 1) {
// echo '添加成功, 添加记录的主键是: ' . $pdo->lastInsertId();
//} else {
// echo '添加失败';
// print_r($stmt->errorInfo());
//}
//更新
//$sql = "UPDATE `users` SET `name` = ? WHERE `id`=?";
//$stmt = $db->prepare($sql);
//$stmt->execute(['zzz', 3]);
// 判断是否执行成功
//if ($stmt->rowCount() === 1) {
// echo '更新成功';
//} else {
// echo '没有记录被更新';
// print_r($stmt->errorInfo());
//}
//删除
$sql = "DELETE FROM `users` WHERE `id`=:id";
$stmt = $db->prepare($sql);
$stmt->execute([':id' => 3]);
// 判断是否执行成功
if ($stmt->rowCount() === 1) {
echo '删除成功';
}
?>
本节课我们学习了PDO操作数据库,通过本节课的学习对PDO知识进行重写认识,对知识点印象更加深刻,在完成作业的时候又进行了查漏补缺。