Blogger Information
Blog 9
fans 0
comment 0
visits 7981
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO、类自动加载、数据库用户表增删改查小案例
若是梦终会醒
Original
727 people have browsed it

用户表增删改查小案例

1.1 index.php

  1. <?php
  2. namespace pdo_edu;
  3. use MyPDO;
  4. //自动加载类
  5. spl_autoload_register(function ($class_name) {
  6. require "./{$class_name}.class.php";
  7. });
  8. //连接数据库
  9. $config = require 'config/database.php';
  10. $mypdo = MyPDO::getInstance($config);
  11. //获取用户数据
  12. $list = $mypdo->fetchAll('select * from data_user');
  13. //渲染视图
  14. require './data_user_list.html';
  15. //进行编辑操作
  16. //获取编辑时提交的数据
  17. @$username = trim($_POST['user_name']);
  18. @$password = trim($_POST['user_pass']);
  19. @$id = array_flip($_POST);
  20. @$id = $id['编辑'];
  21. if ($_POST) {
  22. $sql = "UPDATE `data_user` SET `user_name` = '{$username}',`user_pass`='{$password}' WHERE `user_id`={$id}";
  23. $update = $mypdo->exec($sql);
  24. }
  25. //添加用户
  26. $booladd = $_GET['add_user'] ?? 0;
  27. if ($booladd) {
  28. $addname = time();
  29. $sql = "INSERT `data_user` SET `user_name` = '{$addname}',`user_pass`='0000' ";
  30. $insert = $mypdo->exec($sql);
  31. }
  32. //删除用户
  33. $booldel = $_GET['del'] ?? 0;
  34. if ($booldel) {
  35. $sql = "DELETE FROM `data_user` WHERE `user_id`={$booldel}";
  36. $del = $mypdo->exec($sql);
  37. }

1.2 data_user_list.html 渲染视图

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>用户管理</title>
  7. </head>
  8. <body>
  9. <a href="?">刷新当前页</a>
  10. <a href="?add_user=1">添加用户</a>
  11. <table border='1' width='980' bordercolor='#000'>
  12. <tr>
  13. <th>用户ID</th>
  14. <th>用户名</th>
  15. <th>用户密码</th>
  16. <th>操作</th>
  17. </tr>
  18. <?php foreach($list as $rows):?>
  19. <form action="?" method="post">
  20. <tr>
  21. <td>
  22. <?=$rows['user_id']?>
  23. </td>
  24. <td>
  25. <input type="text" name="user_name" value=" <?=$rows['user_name']?>">
  26. </td>
  27. <td>
  28. <input type="text" name="user_pass" value=" <?=$rows['user_pass']?>">
  29. </td>
  30. <td><input type="submit" value="编辑" name="<?=$rows['user_id']?>"><span>-----</span><a href="?del=<?=$rows['user_id']?>">删除</a></td>
  31. </tr>
  32. </form>
  33. <?php endforeach;?>
  34. </table>
  35. </body>
  36. </html>

1.3 MyPDO.class.php 自定义PDO

  1. <?php
  2. class MyPDO {
  3. private $type; //数据库类别
  4. private $host; //主机地址
  5. private $port; //端口号
  6. private $dbname; //数据库名
  7. private $charset; //字符集
  8. private $user; //用户名
  9. private $pwd; //密码
  10. private $pdo; //保存PDO对象
  11. private static $instance;
  12. private function __construct($param) {
  13. $this->initParam($param);
  14. $this->initPDO();
  15. $this->initException();
  16. }
  17. private function __clone() {
  18. }
  19. public static function getInstance($param=array()){
  20. if(!self::$instance instanceof self)
  21. self::$instance=new self($param);
  22. return self::$instance;
  23. }
  24. //初始化参数
  25. private function initParam($param){
  26. $this->type=$param['type']??'mysql';
  27. $this->host=$param['host']??'127.0.0.1';
  28. $this->port=$param['port']??'3306';
  29. $this->dbname=$param['dbname']??'data';
  30. $this->charset=$param['charset']??'utf8';
  31. $this->user=$param['user']??'root';
  32. $this->pwd=$param['pwd']??'root';
  33. }
  34. //初始化PDO
  35. private function initPDO(){
  36. try{
  37. $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
  38. $this->pdo=new PDO($dsn, $this->user, $this->pwd);
  39. } catch (PDOException $ex) {
  40. $this->showException($ex);
  41. exit;
  42. }
  43. }
  44. //显示异常
  45. private function showException($ex,$sql=''){
  46. if($sql!=''){
  47. echo 'SQL语句执行失败<br>';
  48. echo '错误的SQL语句是:'.$sql,'<br>';
  49. }
  50. echo '错误编号:'.$ex->getCode(),'<br>';
  51. echo '错误行号:'.$ex->getLine(),'<br>';
  52. echo '错误文件:'.$ex->getFile(),'<br>';
  53. echo '错误信息:'.$ex->getMessage(),'<br>';
  54. }
  55. //设置异常模式
  56. private function initException(){
  57. $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  58. }
  59. //执行增、删、改操作
  60. public function exec($sql){
  61. try{
  62. return $this->pdo->exec($sql);
  63. } catch (PDOException $ex) {
  64. $this->showException($ex, $sql);
  65. exit;
  66. }
  67. }
  68. //获取自动增长的编号
  69. public function lastInsertId(){
  70. return $this->pdo->lastInsertId();
  71. }
  72. //判断匹配的类型
  73. private function fetchType($type){
  74. switch ($type){
  75. case 'num':
  76. return PDO::FETCH_NUM;
  77. case 'both':
  78. return PDO::FETCH_BOTH;
  79. case 'obj':
  80. return PDO::FETCH_OBJ;
  81. default:
  82. return PDO::FETCH_ASSOC;
  83. }
  84. }
  85. //获取所有数据 ,返回二维数组
  86. public function fetchAll($sql,$type='assoc'){
  87. try{
  88. $stmt=$this->pdo->query($sql); //获取PDOStatement对象
  89. $type= $this->fetchType($type); //获取匹配方法
  90. return $stmt->fetchAll($type);
  91. } catch (Exception $ex) {
  92. $this->showException($ex, $sql);
  93. }
  94. }
  95. //获取一维数组
  96. public function fetchRow($sql,$type='assoc'){
  97. try{
  98. $stmt=$this->pdo->query($sql); //获取PDOStatement对象
  99. $type= $this->fetchType($type); //获取匹配方法
  100. return $stmt->fetch($type);
  101. } catch (Exception $ex) {
  102. $this->showException($ex, $sql);
  103. exit;
  104. }
  105. }
  106. //返回一行一列
  107. public function fetchColumn($sql){
  108. try{
  109. $stmt=$this->pdo->query($sql);
  110. return $stmt->fetchColumn();
  111. } catch (Exception $ex) {
  112. $this->showException($ex, $sql);
  113. exit;
  114. }
  115. }
  116. }

3.4 创建config配置文件夹 写入 database.php 数据库配置文件

  1. <?php
  2. namespace pdo_edu;
  3. // 数据库连接配置参数
  4. return [
  5. // 数据库的类型
  6. 'type' => $type ?? 'mysql',
  7. // 数据库默认主机
  8. 'host' => $host?? 'localhost',
  9. // 默认数据库
  10. 'dbname'=> $dbname ?? 'phpedu',
  11. // 默认字符编码集
  12. 'charset'=> $charset ?? 'utf8',
  13. // 默认端口号
  14. 'port'=> $port ?? '3306',
  15. // 默认的用户名
  16. 'user'=> $username ?? 'root',
  17. // 默认的用户密码
  18. 'pwd'=> $password ?? 'root',
  19. ];

效果图:

查:

改:

增:

删:

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
2 comments
王小飞 2020-05-08 14:31:52
这里面很多参数都看不懂
2 floor
王小飞 2020-05-08 14:02:09
厉害!好像写出了用户管理中心
1 floor
Author's latest blog post