Blogger Information
Blog 36
fans 0
comment 0
visits 28228
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库操作——PDO
phpcn_u202398
Original
604 people have browsed it

1、连接数据库

代码示例
  1. <?php
  2. namespace edu;
  3. use Exception;
  4. use PDO;
  5. $conf = require 'conf.php';
  6. $type = $conf['type'];
  7. $host = $conf['host'];
  8. $dbname = $conf['dbname'];
  9. $username = $conf['username'];
  10. $password = $conf['password'];
  11. $dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
  12. try {
  13. $db = new PDO($dsn, $username, $password);
  14. } catch (Exception $e) {
  15. echo '错误原因: ' . $e->getMessage();
  16. }
  17. ?>

操作数据库

代码示例
  1. <?php
  2. namespace edu;
  3. use PDO;
  4. //连接数据库
  5. require 'common/db.php';
  6. //查询语句
  7. //$sql = 'select * from users';
  8. //$stmt = $db->prepare($sql);
  9. //$stmt->execute();
  10. //foreach($stmt as $val){
  11. // $date = date('Y年m月d日', $val['add_time']);
  12. // printf('ID=%s;Name=%s;Email=%s;Add_time=%s',$val['id'],$val['name'],$val['email'],$date);
  13. //}
  14. //插入语句
  15. //$sql = "INSERT `users` SET `name`= ? , `email`=?,`add_time`=?";
  16. //$stmt = $db->prepare($sql);
  17. //$date = time();
  18. //$data = ['qqq', '2343@qq.com', $date];
  19. //$stmt->execute($data);
  20. //if ($stmt->rowCount() === 1) {
  21. // echo '添加成功, 添加记录的主键是: ' . $pdo->lastInsertId();
  22. //} else {
  23. // echo '添加失败';
  24. // print_r($stmt->errorInfo());
  25. //}
  26. //更新
  27. //$sql = "UPDATE `users` SET `name` = ? WHERE `id`=?";
  28. //$stmt = $db->prepare($sql);
  29. //$stmt->execute(['zzz', 3]);
  30. // 判断是否执行成功
  31. //if ($stmt->rowCount() === 1) {
  32. // echo '更新成功';
  33. //} else {
  34. // echo '没有记录被更新';
  35. // print_r($stmt->errorInfo());
  36. //}
  37. //删除
  38. $sql = "DELETE FROM `users` WHERE `id`=:id";
  39. $stmt = $db->prepare($sql);
  40. $stmt->execute([':id' => 3]);
  41. // 判断是否执行成功
  42. if ($stmt->rowCount() === 1) {
  43. echo '删除成功';
  44. }
  45. ?>

学习总结

本节课我们学习了PDO操作数据库,通过本节课的学习对PDO知识进行重写认识,对知识点印象更加深刻,在完成作业的时候又进行了查漏补缺。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:是不是觉得pdo其实挺简单的
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