Blogger Information
Blog 30
fans 0
comment 1
visits 21956
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0211MySQLi常见CURD操作+接口实战实例
Admin
Original
547 people have browsed it

MySQLi常见CURD操作+接口实战实例

MySQLi常见CURD操作

首先是MySQL一些常用类

  • mysqli代表PHP于Mysql数据库类里面的一个连接;
  • mysqli_stmt 代表一条预编译的sql语句
  • mysqli_result 代表一个从数据库查询中的结果集;

MySQL常用类方法

  • __construct($host,$username,$password,$dbname,$port,$socket) 数据库连接
  • select_db() 默认数据库选择
  • set_charset() 数据库编码
  • stmt_init() 初始化一条语句并且返回一个mysqli_stmt类实例 (其实用的时候不写好像也不会出错)
    Mysqli_STMT类常用属性/方法
  • prepare() 预处理一条SQL语句
  • bind_param() 将变量绑定至prepare中
  • bind_result() 将变量参数保存到prepared语句,用于结果储存(说人话就是你查了啥,按照顺序绑定到变量方便你到时候fetch)
  • fetch() 将prepare语句中的结果按照bind_result中所绑定的数据输出
  • execute() 执行一条prepare预处理语句
  • get_result() 获取prepare语句中的结果,返回一个结果集对象mysqli_res
  • free_result() 释放prepare所占的运行内存
  • affected_rows 返回 增删改 所影响的函数
  • insert_id 返回上次insert插入的ID
  • $stmt-error 返回错误语句
  • close() 关闭查询语句

Mysqli_常用类result

  • fetch_array()获取mysqli_result对象中的结果集 带有索引数组和关联数组形式(就是这个和下面2个都只拿一条)
  • fetch_row() 同上仅为索引数组
  • fetch_assoc() 同上仅为关联数组
  • fetch_all(MYSQLI_ASSOC/ROW) 获取mysqli_result对象中所有的结果集 带有索引数组和关联数组形式(这个一下子拿全部)
  • data_seek() 指针复位
  • free_result() 释放prepare所占的运行内存

开始使用常用CURD操作

INSERT操作

  1. namespace chapter2;
  2. // 采用面向对象方式来写要导入mysqli
  3. use mysqli;
  4. // MYSQLI 操作数据库
  5. $mysqli = new mysqli('localhost','root','root','xiaoyu');
  6. //设置字符集
  7. $mysqli->set_charset('utf8');
  8. // 创建一条SQL语句 :name命名占位 ?索引占位
  9. $sql = 'INSERT `users` SET `name`=?,`email`=?,`password`=?,`register_time`=?;';
  10. //预处理方式
  11. $stmt = $mysqli->stmt_init();
  12. //准备执行一条sql语句
  13. $stmt->prepare($sql);
  14. //占位参数绑定
  15. $stmt->bind_param('sssi',$name,$email,$password,$register_time);
  16. //将值写入
  17. $users = ['周小雨','1016673080@qq.com','xiaoyu',time()];
  18. list($name,$email,$password,$register_time)=$users;
  19. //执行语句
  20. $stmt->execute();
  21. //3.处理结果
  22. if($stmt->affected_rows >=1){
  23. echo '添加成功,新纪录的主键Id:'.$stmt->insert_id;
  24. }else{
  25. echo '添加失败'.$stmt->error;
  26. }

Delete操作

  1. namespace chapter2;
  2. use mysqli;
  3. //数据库连接
  4. $mysqli=new mysqli('localhost','root','root','xiaoyu');
  5. //设置字符集
  6. $mysqli->set_charset('utf8');
  7. //写一条改数据的SQL
  8. $sql = 'DELETE FROM `users` WHERE `id`=? ;';
  9. //使用预处理
  10. $stmt = $mysqli->stmt_init();
  11. //准备一个将要执行的SQL
  12. $stmt->prepare($sql);
  13. //绑定参数
  14. $id = 7;
  15. $stmt->bind_param('i',$id);
  16. $stmt->execute();
  17. if($stmt->affected_rows >= 1){
  18. echo '删除成功';
  19. }else{
  20. echo '删除失败'.$stmt->error;
  21. }
  22. $stmt->close();

Update操作

  1. namespace chapter2;
  2. use mysqli;
  3. //数据库连接
  4. $mysqli=new mysqli('localhost','root','root','xiaoyu');
  5. //设置字符集
  6. $mysqli->set_charset('utf8');
  7. //写一条改数据的SQL
  8. $sql = 'UPDATE `users` SET `name`=?,`email`=? WHERE `id`=? ;';
  9. //使用预处理
  10. $stmt = $mysqli->stmt_init();
  11. //准备一个将要执行的SQL
  12. $stmt->prepare($sql);
  13. //绑定参数
  14. $datas = ['小雨1','23232@qq.com',8];
  15. list($name,$email,$id)=$datas;
  16. $stmt->bind_param('ssi',$name,$email,$id);
  17. $stmt->execute();
  18. if($stmt->affected_rows >= 1){
  19. echo '更新成功';
  20. }else{
  21. echo '更新失败'.$stmt->error;
  22. }
  23. $stmt->close();

Select 通过mysqli_result

  1. namespace chapter2;
  2. use mysqli;
  3. $mysqli = new mysqli('localhost','root','root','xiaoyu');
  4. $mysqli->set_charset('utf8');
  5. $sql = 'SELECT `id`,`name`,`email` FROM `users` WHERE `id`>?;';
  6. $stmt=$mysqli->stmt_init();
  7. $stmt->prepare($sql);
  8. $id=4;
  9. $stmt->bind_param('i',$id);
  10. $stmt->execute();
  11. //获取结果集对象
  12. $result=$stmt->get_result();
  13. //fetch_rows() 索引
  14. //fetch_assoc() 关联
  15. //fetch_array 都有
  16. while($user = $result->fetch_assoc())
  17. {
  18. echo $user['id'].'=>'.$user['name'].'=>'.$user['email'].'</br>';
  19. }
  20. //数据表指针复位 归零 将指针指向0;
  21. $result->data_seek(0);
  22. echo '<hr>';
  23. $users = $result->fetch_all(MYSQLI_ASSOC);
  24. foreach ($users as $value) {
  25. echo "{$value['id']} : {$value['name']} ==> {$value['email']} <br>";
  26. }
  27. //4.结束操作
  28. //释放结果集
  29. $result->free_result();
  30. //关闭数据库链接
  31. $stmt->close();

Select bind_result方式

  1. namespace chapter2;
  2. use mysqli;
  3. $mysqli = new mysqli('localhost','root','root','xiaoyu');
  4. $mysqli->set_charset('utf8');
  5. $sql = 'SELECT `id`,`name`,`email` FROM `users` WHERE `id`>?;';
  6. $stmt=$mysqli->stmt_init();
  7. $stmt->prepare($sql);
  8. $id=4;
  9. $stmt->bind_param('i',$id);
  10. $stmt->execute();
  11. //将结果集中的字段绑定到变量中
  12. $stmt->bind_result($id,$name,$email);
  13. while ($stmt->fetch()) {
  14. echo "$id : $name ---> $email <br>";
  15. }
  16. //4.结束操作
  17. //释放结果集
  18. $stmt->free_result();
  19. //关闭数据库链接
  20. $stmt->close();

接口多态数据库操作实例

首先创建一个数据库连接操作接口iDbParam用来定义接口常量,iDbLink接口中构造方法用来连接数据库,iCURD接口继承前二者加上数据库操作

  1. #接口实战:使用PDO MySQLi实现数据库多态操作
  2. namespace chapter2;
  3. //配置数据库的连接参数:接口常量
  4. interface iDbParam
  5. {
  6. const HOST = 'localhost';
  7. const TYPE = 'mysql';
  8. const DBNAME = 'xiaoyu';
  9. const USER_NAME = 'root';
  10. const PASSWORD = 'root';
  11. const CHARSET = 'utf8';
  12. const PORT = '3306';
  13. }
  14. interface iDbLink
  15. {
  16. //接口中允许有构造方法
  17. public function __construct(...$linkParams);
  18. //接口方法:后面的代码就是用下面的这个主接口
  19. }
  20. interface iCURD extends iDbLink,iDbParam
  21. {
  22. //新增
  23. public function insert(array $data);
  24. //查询
  25. public function select(string $where = '');
  26. //更新
  27. public function update(array $data,string $where);
  28. //删除
  29. public function delete(string $where);
  30. }

接下来就是实现iCURD接口(因为是多态实现,所以我们要写两个实例化)
mysqli

  1. namespace chapter2;
  2. //引入接口文件
  3. require 'mysqliinter.php';
  4. //用mysqli方式
  5. use mysqli;
  6. class Db_MySQLi implements iCURD
  7. {
  8. //连接对象
  9. private $mysqli = null;
  10. //构造方法
  11. public function __construct(...$linkparams)
  12. {
  13. list($host,$username,$password,$dbname)=$linkparams;
  14. $this->mysqli = new mysqli($host,$username,$password,$dbname);
  15. $this->mysqli->set_charset('utf8');
  16. }
  17. public function insert(array $data)
  18. {
  19. $sql = "INSERT `users` SET `name`=?, `email`=?,`password`=?,`register_time`=?";
  20. $stmt = $this->mysqli->prepare($sql);
  21. $stmt->bind_param('sssi',$name,$email,$password,$register_time);
  22. list($name,$email,$password,$register_time)=$data;
  23. $stmt->execute();
  24. return $stmt->affected_rows === 1 ? '新增成功':'新增失败';
  25. }
  26. public function select(string $where = '')
  27. {
  28. $where = empty($where)?$where:'WHERE '.$where;
  29. $sql = "SELECT * FROM `users` {$where}";
  30. echo $sql;
  31. $stmt = $this->mysqli->prepare($sql);
  32. $stmt->execute();
  33. return $stmt->get_result();
  34. }
  35. public function update(array $data,string $where)
  36. {
  37. $params = '';
  38. foreach ($data as $key => $value) {
  39. $params .= "`{$key}` = '{$value}', ";
  40. }
  41. $params=rtrim($params,', ');
  42. //执行更新
  43. $sql = "UPDATE `users` SET {$params} WHERE {$where}";
  44. echo $sql;
  45. // echo $sql;
  46. $stmt = $this->mysqli->prepare($sql);
  47. $stmt->execute();
  48. return $stmt->affected_rows >= 1 ? '更新成功':'更新失败';
  49. }
  50. public function delete(string $where)
  51. {
  52. $sql = "DELETE FROM `users` WHERE {$where}";
  53. $stmt = $this->mysqli->prepare($sql);
  54. $stmt->execute();
  55. return $stmt->affected_rows >= 1 ? '删除成功':'删除失败';
  56. }
  57. }

pdo

  1. <?php
  2. namespace chapter2;
  3. //引入接口文件
  4. require 'mysqliinter.php';
  5. //用pdo方式
  6. use PDO;
  7. class Db_PDO implements iCURD
  8. {
  9. //连接对象
  10. private $pdo = null;
  11. //构造方法
  12. public function __construct(...$linkparams)
  13. {
  14. list($dsn,$username,$password)=$linkparams;
  15. $this->pdo = new PDO($dsn,$username,$password);
  16. }
  17. public function insert(array $data)
  18. {
  19. $sql = 'INSERT `users` SET `name`=?,`email`=?,`password`=?,`register_time`=?;';
  20. $stmt = $this->pdo->prepare($sql);
  21. $stmt->execute($data);
  22. return $stmt->rowCount() === 1 ? '新增成功':'新增失败';
  23. }
  24. public function select(string $where = '')
  25. {
  26. $where = empty($where)?$where:'WHERE '.$where;
  27. $sql = "SELECT * FROM `users` {$where}";
  28. echo $sql;
  29. $stmt = $this->pdo->prepare($sql);
  30. $stmt->execute();
  31. return $stmt->fetchAll(PDO::FETCH_ASSOC);
  32. }
  33. public function update(array $data,string $where)
  34. {
  35. $params = '';
  36. foreach ($data as $key => $value) {
  37. $params .= "`{$key}`='{$value}', ";
  38. }
  39. $params=rtrim($params,', ');
  40. //执行更新
  41. var_dump($params);
  42. $sql = "UPDATE `users` SET {$params} WHERE {$where}";
  43. echo $sql;
  44. $stmt = $this->pdo->prepare($sql);
  45. $stmt->execute();
  46. return $stmt->rowCount() >= 1 ? '更新成功':'更新失败';
  47. }
  48. public function delete(string $where)
  49. {
  50. $sql = "DELETE FROM `users` WHERE {$where}";
  51. $stmt = $this->pdo->prepare($sql);
  52. $stmt->execute();
  53. return $stmt->rowCount() >= 1 ? '删除成功':'删除失败';
  54. }
  55. }

然后我们创建一个公共类来进行调用

  1. namespace chapter2;
  2. //通用类:数据库操作,面向接口实现多态
  3. use chapter2\iCURD;
  4. class DB
  5. {
  6. public static function insert(iCURD $db,array $data)
  7. {
  8. return $db->insert($data);
  9. }
  10. // 查询
  11. public static function select(iCURD $db, string $where = '')
  12. {
  13. return $db->select($where);
  14. }
  15. // 更新
  16. public static function update(iCURD $db, array $data, string $where='')
  17. {
  18. return $db->update($data, $where);
  19. }
  20. // 删除
  21. public static function delete(iCURD $db, string $where='')
  22. {
  23. return $db->delete($where);
  24. }
  25. }
  1. //接下来就是调用
  2. namespace chapter2;
  3. require 'mysqli_demo.php';
  4. require 'DB.php';
  5. use mysqli;
  6. //使用mysqli类来增删改查
  7. //声明一下用接口多态的mysqli类
  8. $link = new Db_MySQLi(iDbParam::HOST,iDbParam::USER_NAME,iDbParam::PASSWORD,iDbParam::DBNAME);
  9. //------------------------分割线----------------------------------------
  10. namespace chapter2;
  11. //导入pdo类
  12. //导入公共操作类
  13. require 'pdo_demo.php';
  14. require 'DB.php';
  15. $dsn = iDbParam::TYPE.':'.'dbname='.iDbParam::DBNAME.';host='.iDbParam::HOST;
  16. $user = iDbParam::USER_NAME;
  17. $password = iDbParam::PASSWORD;
  18. $link = new Db_PDO($dsn,$user,$password);
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