PDO预处理对数据的增、删、查、改操作

编辑: admin 分类: 电脑知识 发布时间: 2023-06-14 来源:互联网
PDO预处理对数据操作

增:insert

  1. $username = '刘德华';
  2. $password = password_hash('123456', PASSWORD_BCRYPT);
  3. $sql = "INSERT `iuser` SET `username`= :username,`password`= :password ";
  4. $stmt = $db->prepare($sql);
  5. $stmt->bindValue(":username",$username);
  6. $stmt->bindValue(":password",$password);
  7. $stmt->debugDumpParams();
  8. $stmt->execute();

sql语句打印结果:(添加成功)

  1. SQL: [63] INSERT `iuser` SET `username`= :username,`password`= :password Params: 2
  2. Key: Name: [9] :username paramno=-1 name=[9] ":username" is_param=1 param_type=2
  3. Key: Name: [9] :password paramno=-1 name=[9] ":password" is_param=1 param_type=2

改:update

  1. $username = '刘德华';
  2. $email = '123456@qq.com';
  3. $sql = "UPDATE `iuser` SET `email`=:email WHERE `username`=:username";
  4. $stmt = $db->prepare($sql);
  5. $stmt->bindValue(":email",$email);
  6. $stmt->bindValue(":username", $username);
  7. $stmt->debugDumpParams();
  8. $stmt->execute();

sql语句打印结果:(修改成功)

  1. 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

  1. $sql = 'SELECT id,username FROM iuser WHERE id > ?';
  2. $stmt = $db->prepare($sql);
  3. if ($stmt->execute([3])) {
  4. $users = $stmt->fetchAll();
  5. foreach ($users as $user) {
  6. extract($user);
  7. vprintf("%d: %s\n", [$id, $username]);
  8. }
  9. } else {
  10. die('查询失败:' . $stmt->errorInfo());
  11. }

查询结果:

  1. 4: 西门庆 5: 易烊千玺 6: 刘德华

删:delete

  1. $sql = 'delete from iuser where id = ?';
  2. if (!stristr($sql, 'where')) {
  3. die('禁止无条件刪除');
  4. }
  5. $stmt = $db->prepare($sql);
  6. if ($stmt->execute([6])) {
  7. // $stmt->debugDumpParams();
  8. // die;
  9. if ($stmt->rowCount() > 0) {
  10. echo '删除成功';
  11. } else {
  12. echo '没有记录被删除';
  13. }
  14. } else {
  15. die('删除失败: ' . $stmt->errorInfo());
  16. }

删除成功。

总结:

数据库操作确实有点麻烦,稍有差错就失败了;?替代只会execute时传参,:username可以绑定;用的时候再多练吧!

【转自:盐城网站建设公司 http://www.1234xp.com/yancheng.html 复制请保留原URL】