Blogger Information
Blog 33
fans 0
comment 0
visits 17022
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
CURD 操作,PDO 本质\原理,使用预处理的原因
lucaslwk
Original
619 people have browsed it

CURD 操作,PDO 本质\原理,使用预处理的原因

CURD 操作

curd

  1. <?php
  2. namespace pdo;
  3. //连接数据库
  4. require __DIR__ . '/config/connect.php';
  5. //插入 INSERT 表名 SET 字段1=值1,字段2=值2,...
  6. //?关键字全大写,表名字段名使用`反引号
  7. $sqlInsert = 'INSERT `staff` SET `name`=?,`gender`=?,`email`=?';
  8. //* '?'匿名占位符,':字段名'命名占位符
  9. //* $sqlInsert = 'INSERT `staff` SET `name`=:name,`gender`=:gender,`email`=:email';
  10. //创建SQL语句模板对象
  11. $stmt = $db->prepare($sqlInsert);
  12. $stmt->execute(['张三', '1', 'z3@qq.com']);
  13. $stmt->execute(['李四', '0', 'l4@qq.com']);
  14. $stmt->execute(['王五', '1', 'w5@qq.com']);
  15. $stmt->execute(['赵六', '0', 'z6@qq.com']);
  16. // *若条件来自于外部例如url中的get参数
  17. //* $stmt->execute([':id'=?$_GET['id'],':gender'=?$_GET['gender'],':email'=?$_GET['email']]);
  18. include __DIR__ . '/check.php';
  19. //更新 UPDATE 表名 SET 字段1=值1,字段2=值2,... WHERE 更新条件
  20. $sqlUpdate = 'UPDATE `staff` SET `name`=? WHERE `id`=?';
  21. $stmt = $db->prepare($sqlUpdate);
  22. $stmt->execute(['王三', '3']);
  23. include __DIR__ . '/check.php';
  24. //删除 DELETE FROM 表名 WHERE 删除条件
  25. $sqlUpdate = 'DELETE FROM `staff` WHERE `id`=?';
  26. $stmt = $db->prepare($sqlUpdate);
  27. $stmt->execute(['3']);
  28. include __DIR__ . '/check.php';
  29. //查询 SELECT 字段列表 FROM 表名 WHERE 查询条件
  30. $sqlUpdate = 'SELECT * FROM `staff` WHERE `id`<=?';
  31. $stmt = $db->prepare($sqlUpdate);
  32. $stmt->execute(['10']);
  33. include __DIR__ . '/check.php';
  34. //?单次查询
  35. //FETCH默认会返回关联和索引两部分
  36. //方法一:$stmt->fetch(PDO::FETCH_ASSOC) PDO::FETCH_ASSOC只取关联部分
  37. printf('<pre>%s</pre>', print_r($stmt->fetch(), true));
  38. //extract($stmt->fetch());
  39. //echo "$id,$name,$gender,$email";
  40. //?多条查询
  41. //printf('<pre>%s</pre>', print_r($stmt->fetchAll(), true));
  42. foreach ($stmt->fetchAll() as $key) {
  43. extract($key);
  44. if ($gender === '1') {
  45. $gender = '男';
  46. } else $gender = '女';
  47. echo "$id---$name---$gender---$email<br>";
  48. //printf('<pre>%s</pre>', print_r($key, true));
  49. }

PDO 本质\原理

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

使用预处理的原因

  1. 预处理:可以防止sql注入攻击,可以实现数据延迟绑定
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