Blogger Information
Blog 38
fans 0
comment 0
visits 18548
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示数据库的CURD操作、PDO的本质与原理是什么?为什么要用预处理?
Blackeye
Original
517 people have browsed it

1
2

2. 描述PDO的本质与原理是什么? 为什么要用预处理?

PDO本质是一个包含对数据库相关操作的类

PDO原理是创建一个实例对象,然后调用类中的相关方法对选中的数据库进行操作

预处理:可以防止sql注入攻击,可以实现数据延迟绑定

  1. <?php
  2. namespace php_cn;
  3. use PDO;
  4. // 1. 实例演示数据库的CURD操作
  5. // 连接数据库
  6. $dsn = "mysql:host=localhost;dbname=phpedu;port:3306;charset=utf8;";
  7. $db = new PDO($dsn,'root','root');
  8. // 增加
  9. $sql = 'INSERT `staff` SET `name`=?,`gender`=?,`email`=?';
  10. $stmt = $db->prepare($sql);
  11. $stmt->execute(['Dave',0,'Dave@qq.com']);
  12. $stmt->execute(['John',0,'John@qq.com']);
  13. $stmt->execute(['Frank',0,'Frank@qq.com']);
  14. $stmt->execute(['Jane',1,'Jane@qq.com']);
  15. $stmt->execute(['David',0,'David@qq.com']);
  16. $stmt->execute(['Lee',0,'Lee@qq.com']);
  17. $stmt->execute(['Demon',0,'Demon@qq.com']);
  18. $stmt->execute(['Ash',0,'Ash@qq.com']);
  19. $stmt->execute(['Zarah',1,'Zarah@qq.com']);
  20. $stmt->execute(['Sarah',1,'Sarah@qq.com']);
  21. // 删除
  22. $sql = 'DELETE FROM `staff` WHERE `id`=?';
  23. $stmt = $db->prepare($sql);
  24. $stmt->execute([4]);
  25. // 修改
  26. $sql = 'UPDATE `staff` SET `name`=? WHERE `id`=?';
  27. $stmt = $db->prepare($sql);
  28. $stmt->execute(['meimei',5]);
  29. // 查询
  30. $sql = 'SELECT `id`,`name` FROM `staff` WHERE `id`>?';
  31. $stmt = $db->prepare($sql);
  32. $stmt->execute([3]);
  33. $staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);
  34. foreach($staffs as $staff){
  35. printf("<pre>%s</pre>",print_r($staff,true));
  36. }
  37. // 关闭数据库
  38. $db = null;
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!