Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
增:insert
$username = '刘德华';
$password = password_hash('123456', PASSWORD_BCRYPT);
$sql = "INSERT `iuser` SET `username`= :username,`password`= :password ";
$stmt = $db->prepare($sql);
$stmt->bindValue(":username",$username);
$stmt->bindValue(":password",$password);
$stmt->debugDumpParams();
$stmt->execute();
sql语句打印结果:(添加成功)
SQL: [63] INSERT `iuser` SET `username`= :username,`password`= :password Params: 2
Key: Name: [9] :username paramno=-1 name=[9] ":username" is_param=1 param_type=2
Key: Name: [9] :password paramno=-1 name=[9] ":password" is_param=1 param_type=2
改:update
$username = '刘德华';
$email = '123456@qq.com';
$sql = "UPDATE `iuser` SET `email`=:email WHERE `username`=:username";
$stmt = $db->prepare($sql);
$stmt->bindValue(":email",$email);
$stmt->bindValue(":username", $username);
$stmt->debugDumpParams();
$stmt->execute();
sql语句打印结果:(修改成功)
SQL: [60] UPDATE `iuser` SET `email`=:email WHERE `username`=:username Params: 2 Key: Name: [6] :email paramno=-1 name=[6] ":email" is_param=1 param_type=2 Key: Name: [9] :username paramno=-1 name=[9] ":username" is_param=1 param_type=2
查:select
$sql = 'SELECT id,username FROM iuser WHERE id > ?';
$stmt = $db->prepare($sql);
if ($stmt->execute([3])) {
$users = $stmt->fetchAll();
foreach ($users as $user) {
extract($user);
vprintf("%d: %s\n", [$id, $username]);
}
} else {
die('查询失败:' . $stmt->errorInfo());
}
查询结果:
4: 西门庆 5: 易烊千玺 6: 刘德华
删:delete
$sql = 'delete from iuser where id = ?';
if (!stristr($sql, 'where')) {
die('禁止无条件刪除');
}
$stmt = $db->prepare($sql);
if ($stmt->execute([6])) {
// $stmt->debugDumpParams();
// die;
if ($stmt->rowCount() > 0) {
echo '删除成功';
} else {
echo '没有记录被删除';
}
} else {
die('删除失败: ' . $stmt->errorInfo());
}
删除成功。
数据库操作确实有点麻烦,稍有差错就失败了;?替代只会execute时传参,:username可以绑定;用的时候再多练吧!