Blogger Information
Blog 38
fans 0
comment 0
visits 22641
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO预处理对数据的增、删、查、改操作
一个好人
Original
764 people have browsed it

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可以绑定;用的时候再多练吧!

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post