Blogger Information
Blog 64
fans 6
comment 2
visits 82810
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP 数据库PDO操作
王娇
Original
786 people have browsed it

学习总结

  • 掌握了通过PHP中的PDO类实现与数据库的连接
  • PDO可以加载多种类型的数据库引擎,如果更换数据库,只需要更改数据库连接参数中的dsn->type即可
  • 可以把数据库的连接和增删改查封装在一个类中方便使用

1.自动加载一个PDO的连接类 DBconn.php

  1. <?php
  2. namespace compotents\conn
  3. {
  4. use Exception;
  5. use PDO;
  6. class DBconn
  7. {
  8. private $config = [];
  9. protected $dbConn;
  10. public function __construct($dbName = 'db_phpstudy',$userName = 'root',$passWord ='root')
  11. {
  12. $this ->config['type'] = 'mysql';
  13. $this ->config['host'] = 'localhost';
  14. $this ->config['dbName'] = $dbName;
  15. $this ->config['charset'] = 'utf8';
  16. $this ->config['port'] = '3306';
  17. $this ->config['userName'] = $userName;
  18. $this ->config['passWord'] = $passWord;
  19. $this ->connect();
  20. }
  21. public function connect()
  22. {
  23. //拆分数组,键名当做变量名,值当做变量的值,拆分成数据库连接的变量
  24. extract($this->config,EXTR_PREFIX_SAME,'config');
  25. //pdo连接必须的dsn;
  26. $dsn = sprintf('%s:host=%s;dbname=%s;',$type,$host,$dbName);
  27. try
  28. {
  29. $this->dbConn = new PDO($dsn,$userName,$passWord);
  30. }
  31. catch(Exception $e)
  32. {
  33. die($e->getMessage());
  34. }
  35. }
  36. //查询返回查询结果集
  37. public function select($table,$where)
  38. {
  39. $sql = "SELECT * FROM `$table` WHERE $where";
  40. //pdo的预处理对象
  41. $stmt = $this->dbConn->prepare($sql);
  42. $stmt->execute();
  43. $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
  44. return $records;
  45. }
  46. //插入记录,输出是否成功添加记录
  47. public function insert($table,$insData)
  48. {
  49. //把传入的添加数据的数组转换为一个SQL添加字符串
  50. $insertSet = $this->toSqlStr($insData);
  51. //pdo的预处理对象
  52. $sql = "INSERT `$table` SET $insertSet";
  53. $stmt = $this->dbConn->prepare($sql);
  54. $stmt->execute();
  55. $rowCount = $stmt->rowCount();//返回受影响的记录数
  56. if($rowCount >= 1):
  57. echo $rowCount,'条记录添加成功','<br>';
  58. else:
  59. echo '添加记录失败,原因:', $stmt ->errorInfo(),'<br>';
  60. endif;
  61. }
  62. //更新记录,输出更新几条记录
  63. public function update($table,$data,$where)
  64. {
  65. //把传入的添加数据的数组转换为一个SQL添加字符串
  66. $updateSet = $this->toSqlStr($data);
  67. //pdo的预处理对象
  68. $sql = "UPDATE `$table` SET $updateSet WHERE $where";
  69. try
  70. {
  71. $stmt = $this->dbConn->prepare($sql);
  72. $stmt->execute();
  73. $rowCount = $stmt->rowCount();//返回受影响的记录数
  74. if($rowCount === 0):
  75. echo '没有记录被更新<br>';
  76. else:
  77. echo $rowCount,'条记录更新成功','<br>';
  78. endif;}
  79. catch(Exception $e)
  80. {
  81. echo '更新失败,原因:',$e->getMessage();
  82. }
  83. }
  84. //删除记录,输出是否删除成功
  85. public function delete($table,$where)
  86. {
  87. $sql = "DELETE FROM $table WHERE $where";
  88. //pdo的预处理对象
  89. $stmt = $this->dbConn->prepare($sql);
  90. $stmt->execute();
  91. $rowCount = $stmt->rowCount();//返回受影响的记录数
  92. if($rowCount === 0):
  93. echo '没有记录被删除<br>';
  94. else:
  95. echo $rowCount,'条记录删除成功','<br>';
  96. endif;
  97. }
  98. public function toSqlStr($arr):string
  99. {
  100. //把数组的键提取到一个数组中
  101. $keys = array_keys($arr);
  102. //把数组的值提取到一个数组中
  103. $value = array_values($arr);
  104. $con = count($keys);
  105. $sqlStr ='';
  106. for ($i=0;$i<$con;$i++):
  107. if($i===$con-1):
  108. $sqlStr .= " `$keys[$i]`='$value[$i]'";
  109. else:
  110. $sqlStr .= " `$keys[$i]`='$value[$i]' ,";
  111. endif;
  112. endfor;
  113. return $sqlStr;
  114. }
  115. }
  116. }
  117. ?>

2.自动加载文件 autoLoad.php

  1. <?php
  2. try
  3. {
  4. spl_autoload_register(function($className){
  5. //DIRECTORY_SEPARATOR返回当前系统的目录分隔符
  6. //将空间中的分隔符替换成当前系统的目录分隔符
  7. $path = str_replace('\\', DIRECTORY_SEPARATOR, $className);
  8. //__DIR__返回当前文件所在路径
  9. //生成要加载的类文件名称
  10. $file = __DIR__ . DIRECTORY_SEPARATOR . $path . '.php';
  11. // 3. 加载这个文件
  12. require $file;
  13. });
  14. }
  15. catch(Exception $e)
  16. {
  17. $e->getMessage();
  18. }
  19. ?>
  • 文件目录结构

3.对数据库的CURD(增删改查)操作demo1.php

  1. <?php
  2. require 'autoLoad.php';
  3. use compotents\conn\DBconn;
  4. function printUserInfo($records)
  5. {
  6. foreach($records as $record):
  7. echo '用户名:',$record['name'],'<br>';
  8. echo '性别:',$record['sex'],'<br>';
  9. echo '年龄:',$record['age'],'<br>';
  10. echo '<hr>';
  11. endforeach;
  12. }
  13. $user =new DBconn();
  14. $table = 'tb_user';//表名
  15. $where =''; //判断的条件
  16. $data =[];//添加或者更新的数据
  17. //显示所有用户信息
  18. // $records = $user->select('SELECT * FROM `tb_user`');
  19. // printUserInfo($records);
  20. echo '****************显示所有男用户***************','<br>';
  21. //查询操作
  22. $where = '`sex`="男"';
  23. $records = $user->select($table,$where);
  24. printUserInfo($records);
  25. //添加操作
  26. $data = ['name'=>'wangjiao','password'=>'wj123','sex'=>'女','age'=>'14'];
  27. $user->insert($table,$data);
  28. // //更新操作
  29. $where = '`id`>5';
  30. $data = ['name'=>'hugn','password'=>'hugn456','sex'=>'男','age'=>'24'];
  31. $user->update($table,$data,$where);
  32. //添加操作
  33. $where = '`id`>5';
  34. $user->delete($table,$where);
  35. ?>
  • 代码显示效果图
Correcting teacher:天蓬老师天蓬老师

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