登录  /  注册
博主信息
博文 22
粉丝 1
评论 1
访问量 21597
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
PHP中MySQLi常见的CURD操作以及接口多态的实现--***十期线上班
Miss灬懒虫
原创
1382人浏览过

PHP中MySQLi常见的CURD操作以及接口多态的实现

学习总结

在本次学习内容的实践过程中,发现Mysqli相对于PDO的要简洁一些,而且mysql_result的结果集的操作个人感觉也比较简单。

其次,就是无论是PDO还是MySQLi,在访问数据库的步骤上基本是一致的,细节上略有差别而已。

最后,对于接口的多态实现,其本质上,还是利用了接口之间允许继承,并且可以多继承的特性。与此同时,也因为接口仅仅是定义,也就是说接口具备一个接口,允许有多个类进行不同的实现的特性。正是因为这些特性,接口才能很好地实现PHP面向对象开发中的多态

以上仅代表个人观点哦! - _ -

数据库

mysqli 面向对象操作-运行效果

mysqli 面向对象操作-代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 10:57
  7. */
  8. namespace Mysql_data;
  9. use mysqli;
  10. //mysqli 面向对象操作数据库
  11. class MySQLi_Basics{
  12. //新增
  13. public function inter_SQL(){
  14. //1.创建mysqli对象,连接数据库
  15. $mysqli=new mysqli('localhost','root','root888','test');
  16. //2.传入需要---执行的SQL语句
  17. $sql = 'INSERT `tf_users` SET `f_name`=?, `f_password`=?,`f_email`=?,`f_phone`=?,`f_regtime`=?;';
  18. //3.通过stmt_init(),实例化一个预处理对象,防止SQL注入攻击
  19. $stmt=$mysqli->stmt_init();
  20. //3.1 使用预处理对象下的prepare()方法,将SQl注入到预处理对象中
  21. $stmt->prepare($sql);
  22. //参数
  23. $user = ['李木子', sha1('5649725'), 'li_muzi@mayituyu.cn', '1786411111',date('yy-m-d h:i:s',time())];
  24. list($name, $password, $email,$phone,$regtime) = $user;
  25. // 使用预处理对象的 bind_param('参数的类型', 参数列表.....)方法,绑定参数到其中
  26. $stmt->bind_param('sssss', $name, $password, $email, $phone,$regtime);
  27. // 准备完成---执行
  28. $stmt->execute();
  29. // 4. 处理执行的结果
  30. if ($stmt->affected_rows === 1) :
  31. echo '添加成功, 新记录的主键id: ' . $stmt->insert_id;
  32. else :
  33. echo '添加失败' . $stmt->error;
  34. endif;
  35. // 5. 结束操作
  36. // 关闭数据库连接
  37. $stmt->close();
  38. }
  39. //更新
  40. public function update_SQL(){
  41. $mysqli=new mysqli('localhost','root','root888','test');
  42. $sql = "UPDATE `tf_users` SET `f_phone`=?,`f_regtime`=? WHERE `f_id`=?;";
  43. //3.通过stmt_init(),实例化一个预处理对象,防止SQL注入攻击
  44. $stmt=$mysqli->stmt_init();
  45. //3.1 使用预处理对象下的prepare()方法,将SQl注入到预处理对象中
  46. $stmt->prepare($sql);
  47. //参数
  48. $user = ['15867425596',date('yy-m-d h:i:s',time()),2];
  49. list($phone,$regtime,$id) = $user;
  50. // 使用预处理对象的 bind_param('参数的类型', 参数列表.....)方法,绑定参数到其中
  51. $stmt->bind_param('ssi', $phone,$regtime,$id);
  52. // 准备完成---执行
  53. $stmt->execute();
  54. // 4. 处理执行的结果
  55. if ($stmt->affected_rows === 1) :
  56. echo 'ID:'.$id.'的数据更新成功!更新时间:'.$regtime;
  57. else :
  58. echo '更新失败' . $stmt->error;
  59. endif;
  60. // 5. 结束操作
  61. // 关闭数据库连接
  62. $stmt->close();
  63. }
  64. //删除
  65. public function delete_SQL($id){
  66. //1.创建mysqli对象,连接数据库
  67. $mysqli=new mysqli('localhost','root','root888','test');
  68. //2.传入需要---执行的SQL语句
  69. $sql = 'DELETE FROM `tf_users` WHERE `f_id`=?;';
  70. //3.通过stmt_init(),实例化一个预处理对象,防止SQL注入攻击
  71. $stmt=$mysqli->stmt_init();
  72. //3.1 使用预处理对象下的prepare()方法,将SQl注入到预处理对象中
  73. $stmt->prepare($sql);
  74. //参数
  75. $user_id = $id;
  76. // 使用预处理对象的 bind_param('参数的类型', 参数列表.....)方法,绑定参数到其中
  77. $stmt->bind_param('i', $user_id);
  78. // 准备完成---执行
  79. $stmt->execute();
  80. // 4. 处理执行的结果
  81. if ($stmt->affected_rows === 1) :
  82. echo 'ID:'.$user_id.'的数据删除成功!删除时间:'.date('yy-m-d h:i:s',time());
  83. else :
  84. echo '删除失败' . $stmt->error;
  85. endif;
  86. // 5. 结束操作
  87. // 关闭数据库连接
  88. $stmt->close();
  89. }
  90. //查询-1 使用STMT对象查询(预处理对象)
  91. public function select_SQL($id){
  92. //1.创建mysqli对象,连接数据库
  93. $mysqli=new mysqli('localhost','root','root888','test');
  94. //2.传入需要---执行的SQL语句
  95. $sql = 'SELECT `f_name`,`f_email`,`f_regtime` FROM `tf_users` WHERE `f_id`>?;';
  96. //3.通过stmt_init(),实例化一个预处理对象,防止SQL注入攻击
  97. $stmt=$mysqli->stmt_init();
  98. //3.1 使用预处理对象下的prepare()方法,将SQl注入到预处理对象中
  99. $stmt->prepare($sql);
  100. //参数
  101. $user_id = $id;
  102. // 使用预处理对象的 bind_param('参数的类型', 参数列表.....)方法,绑定参数到其中
  103. $stmt->bind_param('i', $user_id);
  104. // 准备完成---执行
  105. $stmt->execute();
  106. // 4. 处理执行的结果
  107. //4.1使用 bind_result()方法,将结果集中的字段绑定在变量上
  108. $stmt->bind_result($name,$email,$regtime);
  109. //4.2 使用fetch()方法,获取结果集中的当前一条记录,并且数据指针会自动下移一个;
  110. while ($stmt->fetch()){
  111. echo '用户名:'.$name.',的邮箱是:'.$email.',用户注册时间:'.$regtime.'<br>';
  112. }
  113. // 5. 结束操作
  114. //5.1 使用 free_result() 释放结果集所占用的内存
  115. $stmt->free_result();
  116. // 关闭数据库连接
  117. $stmt->close();
  118. }
  119. //查询-2 使用
  120. public function select_results($id){
  121. $mysqli=new mysqli('localhost','root','root888','test');
  122. $sql = 'SELECT `f_name`,`f_email`,`f_regtime` FROM `tf_users` WHERE `f_id`>?;';
  123. $stmt=$mysqli->stmt_init();
  124. $stmt->prepare($sql);
  125. $user_id = $id;
  126. $stmt->bind_param('i', $user_id);
  127. $stmt->execute();
  128. //1.使用 get_result(),获取结果集对象
  129. $result=$stmt->get_result();
  130. /*
  131. * 2. 处理执行的结果
  132. * fetch_array(),获取一条记录,包含索引和关联
  133. * fetch_row(),获取一条记录,仅索引部分;
  134. * fetch_assoc()获取一条记录,仅关联部分;
  135. * fetch_all(),一次性获取所有数据(参数为MYSQLI_ASSOC)时,只返回关联部分;
  136. * data_seek(0),索引归 0 复位;
  137. * free_result(),释放结果集所占用的内存;
  138. * */
  139. //循环遍历输出
  140. while ($users=$result->fetch_assoc()){
  141. echo '用户名:'.$users['f_name'].',的邮箱是:'.$users['f_email'].',用户注册时间:'.$users['f_regtime'].'<br>';
  142. }
  143. //索引复位 因为上面以及遍历完了 ,我们下面使用fetch_all一次性返回所有数据,所以需要先将指针复位;
  144. echo '<br>========一次性输出所有========<br>';
  145. $result->data_seek(0);
  146. //fetch_all
  147. $users=$result->fetch_all(MYSQLI_ASSOC);
  148. foreach ($users as $user){
  149. echo '用户名:'.$user['f_name'].',的邮箱是:'.$user['f_email'].',用户注册时间:'.$user['f_regtime'].'<br>';
  150. }
  151. // 5. 结束操作
  152. //5.1 使用 free_result() 释放结果集所占用的内存;
  153. $result->free_result();
  154. // 关闭数据库连接
  155. $stmt->close();
  156. }
  157. }
  158. $mysql_sql=new MySQLi_Basics();
  159. //新增
  160. $mysql_sql->inter_SQL();
  161. echo '<hr>';
  162. //更新
  163. $mysql_sql->update_SQL();
  164. echo '<hr>';
  165. //删除
  166. $mysql_sql->delete_SQL(9);
  167. echo '<hr>';
  168. //查询-1
  169. $mysql_sql->select_SQL(2);
  170. echo '<hr>';
  171. //查询-2
  172. $mysql_sql->select_results(2);
  173. ?>

接口多态—文件目录

运行效果

PDO


MySQLi

DB_interface.php 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 15:27
  7. * Description: 数据访问接口定义
  8. */
  9. /*
  10. * 接口之间允许继承,并且可以多继承。与此同时,一个接口,允许有多个类进行不同的实现。
  11. * 正是因为接口的这些特性,才能使其实现面向对象的 `多态`实现;
  12. * */
  13. namespace Database;
  14. //设置数据库连接参数:默认值
  15. interface inter_DbParam{
  16. const HOST='localhost';
  17. const TYPE='mysql';
  18. const DB_NAME='test';
  19. const USER_NAME='root';
  20. const PASSWORD='root888';
  21. const PORT='3306';
  22. const CHARSET='utf8'; //默认字符集
  23. }
  24. //接口构造方法
  25. interface inter_DbConnection{
  26. //构造方法,
  27. public function __construct(array $connectionParams);
  28. }
  29. //下面是数据库连接接口中,主要被实现的类
  30. interface inter_Execute extends inter_DbParam,inter_DbConnection{
  31. //新增操作,其参数是多个,所以参数是一个数组类型
  32. public function ex_Insert(array $data);
  33. //删除操作,参数是删除数据的条件
  34. public function ex_Delete(string $where);
  35. //更新操作,参数是更新的数据和更新条件
  36. public function ex_Update(array $data,string $where);
  37. //查询操作
  38. public function ex_Select(string $where);
  39. }

DB_pdo.php 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 15:51
  7. * Description: PDO方式,实现数据库访问
  8. */
  9. namespace Database;
  10. //导入PDO
  11. use PDO;
  12. //载入接口文件
  13. require 'DB_interface.php';
  14. class db_PDO implements inter_Execute{
  15. //连接对象
  16. private $pdo=null;
  17. //实现接口中的构造方法
  18. public function __construct(array $connectionParams)
  19. {
  20. //将传入参数 $connectionParams 中的值,分别绑定给指定变量
  21. list($dsn,$username,$password)=$connectionParams;
  22. //实例化PDO对象
  23. $this->pdo=new PDO($dsn,$username,$password);
  24. }
  25. //新增操作
  26. public function ex_Insert(array $data){
  27. $sql="INSERT `tf_users` SET `f_name`=?, `f_password`=?,`f_email`=?,`f_phone`=?,`f_regtime`=?;";
  28. //使用PDO对象的 prepare方法创建预处理对象
  29. $stmt=$this->pdo->prepare($sql);
  30. //执行语句的时候,需要将新增的数据传参给execute()
  31. $stmt->execute($data);
  32. //rowCount()返回受影响的行数
  33. if ($stmt->rowCount()===1){
  34. $message='新增数据成功!';
  35. }else{
  36. $message='新增数据失败!';
  37. }
  38. return$message;
  39. }
  40. //删除操作
  41. public function ex_Delete(string $where){
  42. $sql = 'DELETE FROM `tf_users` WHERE '.$where;
  43. $stmt=$this->pdo->prepare($sql);
  44. $stmt->execute();
  45. //rowCount()返回受影响的行数
  46. if ($stmt->rowCount()===1){
  47. $message='删除数据成功!';
  48. }else{
  49. $message='删除数据失败!';
  50. }
  51. return$message;
  52. }
  53. //更新操作
  54. public function ex_Update(array $data,string $where){
  55. //设置更新的参数
  56. $params='';
  57. foreach ($data as $key=>$value){
  58. $params.="`$key`='$value',";
  59. }
  60. //使用 rtrim() 去掉最后的多于的 逗号
  61. $params=rtrim($params,',');
  62. //执行更新
  63. $sql = "UPDATE `tf_users` SET {$params} WHERE {$where}";
  64. $stmt = $this->pdo->prepare($sql);
  65. $stmt->execute();
  66. //rowCount()返回受影响的行数
  67. if ($stmt->rowCount()===1){
  68. $message='更新数据成功!';
  69. }else{
  70. $message='更新数据失败!';
  71. }
  72. return$message;
  73. }
  74. //查询操作
  75. public function ex_Select(string $where){
  76. //判断传入条件
  77. $where = empty($where) ? '' : ' WHERE ' . $where;
  78. $sql='SELECT * FROM `tf_users` '.$where;
  79. $stmt=$this->pdo->prepare($sql);
  80. $stmt->execute();
  81. //PDO::FETCH_ASSOC 输出关联部分
  82. return $stmt->fetchAll(PDO::FETCH_ASSOC);
  83. }
  84. }

DB_mysqli 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 17:56
  7. * Description: MySQLi方式,实现数据库访问
  8. */
  9. namespace Database;
  10. //导入MySQLi
  11. use mysqli;
  12. //载入接口文件
  13. require 'DB_interface.php';
  14. class db_MySQLi implements inter_Execute{
  15. //连接对象
  16. private $mysqli=null;
  17. //实现接口中的构造方法
  18. public function __construct(array $connectionParams)
  19. {
  20. //将传入参数 $connectionParams 中的值,分别绑定给指定变量
  21. list($host,$username,$password,$dbname)=$connectionParams;
  22. //实例化mysqli
  23. $this->mysqli=new mysqli($host,$username,$password,$dbname);
  24. //设置默认字符集
  25. $this->mysqli->set_charset('utf8');
  26. }
  27. //新增操作
  28. public function ex_Insert(array $data){
  29. $sql="INSERT `tf_users` SET `f_name`=?, `f_password`=?,`f_email`=?,`f_phone`=?,`f_regtime`=?;";
  30. //使用PDO对象的 prepare方法创建预处理对象
  31. $stmt=$this->mysqli->prepare($sql);
  32. //数据绑定
  33. $stmt->bind_param('sssss',$name,$password,$email,$phone,$regtime);
  34. list($name,$password,$email,$phone,$regtime)=$data;
  35. //执行语句的时候,需要将新增的数据传参给execute()
  36. $stmt->execute();
  37. //rowCount()返回受影响的行数
  38. if ($stmt->affected_rows===1){
  39. $message='新增数据成功!';
  40. }else{
  41. $message='新增数据失败!';
  42. }
  43. return$message;
  44. }
  45. //删除操作
  46. public function ex_Delete(string $where){
  47. $sql = 'DELETE FROM `tf_users` WHERE '.$where;
  48. $stmt=$this->mysqli->prepare($sql);
  49. $stmt->execute();
  50. //rowCount()返回受影响的行数
  51. if ($stmt->affected_rows===1){
  52. $message='删除数据成功!';
  53. }else{
  54. $message='删除数据失败!';
  55. }
  56. return$message;
  57. }
  58. //更新操作
  59. public function ex_Update(array $data,string $where){
  60. //设置更新的参数
  61. $params='';
  62. foreach ($data as $key=>$value){
  63. $params.="`$key`='$value',";
  64. }
  65. //使用 rtrim() 去掉最后的多于的 逗号
  66. $params=rtrim($params,',');
  67. //执行更新
  68. $sql = "UPDATE `tf_users` SET {$params} WHERE {$where}";
  69. $stmt = $this->mysqli->prepare($sql);
  70. $stmt->execute();
  71. //rowCount()返回受影响的行数
  72. if ($stmt->affected_rows===1){
  73. $message='更新数据成功!';
  74. }else{
  75. $message='更新数据失败!';
  76. }
  77. return$message;
  78. }
  79. //查询操作
  80. public function ex_Select(string $where){
  81. //判断传入条件
  82. $where = empty($where) ? '' : ' WHERE ' . $where;
  83. $sql='SELECT * FROM `tf_users` '.$where;
  84. $stmt=$this->mysqli->prepare($sql);
  85. $stmt->execute();
  86. //通过 get_result()获取预处理对象的结果集
  87. $results=$stmt->get_result();
  88. return $results;
  89. }
  90. }

DB.php 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 16:34
  7. * Description: DB通用类,面向接口实现PDO、MySQLi的动态支持(多态)
  8. */
  9. namespace Database;
  10. use Database\inter_Execute as iDb;
  11. /*
  12. * DB 通用类中,使用了接口作为 类方法参数,
  13. * 并且在类方法中返回了接口的方法结果;
  14. * */
  15. class DB{
  16. //新增
  17. public static function db_Insert(iDb $db,array $data){
  18. return $db->ex_Insert($data);
  19. }
  20. //删除
  21. public static function db_Delete(iDb $db,string $where){
  22. return $db->ex_Delete($where);
  23. }
  24. //更新
  25. public static function db_Update(iDb $db,array $data,string $where){
  26. return $db->ex_Update($data,$where);
  27. }
  28. //查询
  29. public static function db_Select(iDb $db, $where){
  30. return $db->ex_Select($where);
  31. }
  32. }

Access_pdo.php 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 16:51
  7. * Description: 通过BD类,使用PDO方式访问数据库
  8. */
  9. namespace Database;
  10. //加载文件
  11. require 'DB_pdo.php';
  12. require 'DB.php';
  13. // 拼接 $dsn
  14. $dsn= inter_DbParam::TYPE . ':host='.inter_DbParam::HOST . ';dbname=' . inter_DbParam::DB_NAME . ';charset='.inter_DbParam::CHARSET;
  15. // 拼接数组参数
  16. $paranms=[
  17. $dsn,
  18. inter_DbParam::USER_NAME,
  19. inter_DbParam::PASSWORD
  20. ];
  21. //创建PDO
  22. $link=new db_PDO($paranms);
  23. echo '===========PDO测试============<br>';
  24. // 测试新增操作
  25. echo '消息:'.DB::db_Insert($link,['李继承',sha1('584627'),'zhang_chenghao@mayitiyu.cn','17569842711',date('yy-m-d h:i:s',time())]);
  26. echo '<hr>';
  27. // 测试查询
  28. foreach (DB::db_Select($link, 'f_id > 2') as $user) {
  29. echo '用户名:'.$user['f_name'].',的邮箱是:'.$user['f_email'].',用户注册时间:'.$user['f_regtime'].'<br>';
  30. }
  31. echo '<hr>';
  32. // 更新测试
  33. echo DB::db_Update($link,['f_name'=>'逍遥王子', 'f_email'=>'xiaoyao_wangzi@mayitiyu.cn'], 'f_id=5');
  34. echo '<hr>';
  35. // 删除操作
  36. echo DB::db_Delete($link,'f_id=13');

Access_mysqli.php 文件代码

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/12
  6. * Time: 17:55
  7. * Description: 通过BD类,使用MySQLi方式访问数据库
  8. */
  9. namespace Database;
  10. //加载文件
  11. require 'DB_mysqli.php';
  12. require 'DB.php';
  13. // 拼接数组参数
  14. $paranms=[
  15. inter_DbParam::HOST,
  16. inter_DbParam::USER_NAME,
  17. inter_DbParam::PASSWORD,
  18. inter_DbParam::DB_NAME
  19. ];
  20. //创建PDO
  21. $link=new db_MySQLi($paranms);
  22. echo '===========MySQLi测试============<br>';
  23. // 测试新增操作
  24. echo '消息:'.DB::db_Insert($link,['王重阳',sha1('75264889'),'wang_chongyang@mayitiyu.cn','17569842711',date('yy-m-d h:i:s',time())]);
  25. echo '<hr>';
  26. // 测试查询
  27. foreach (DB::db_Select($link, 'f_id > 2') as $user) {
  28. echo '用户名:'.$user['f_name'].',的邮箱是:'.$user['f_email'].',用户注册时间:'.$user['f_regtime'].'<br>';
  29. }
  30. echo '<hr>';
  31. // 更新测试
  32. echo DB::db_Update($link,['f_name'=>'逍遥王孙', 'f_email'=>'xiaoyao_wangsun@mayitiyu.cn'], 'f_id=5');
  33. echo '<hr>';
  34. // 删除操作
  35. echo DB::db_Delete($link,'f_id=14');

MySQLi 基础知识抄写



批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:命名注意规范, select_SQL, 算什么呢? 要么select_sql, 要么selectSql
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学