PHP的 Mysqli扩展库的多语句执行

时间:2025-04-11 18:35:25

$mysqli->multi_query($sqls);     执行多个sql语句,返回true/false
有结果集时,使用 $mysqli->store_result(); 来获取结果集
使用$mysqli->next_result()来移动结果集指针
使用$mysqli->more_result()来判断是否还有下一个结果集

 

   1: <?php

   2: header("Content-Type:text/html; charset=utf8");

   3:  

   4: $mysqli = new mysqli("localhost","root","1234","test2");

   5:  

   6: if($mysqli->connect_error)

   7: {

   8:     die("连接数据库出错:".$mysqli->connect_error);

   9: }

  10:  

  11:  

  12: // // 增

  13: // $sqls = "insert into userinfo(uName,uAge,uPwd) values('测试07',18,MD5('1234'));";

  14: // // 删

  15: // $sqls .= "delete from userinfo where id=21;";

  16: // // 改

  17: // $sqls .= "update userinfo set uAge=19 where Id=21;";

  18:  

  19: // $result = $mysqli->multi_query($sqls);

  20:  

  21: // if($result){

  22: //     echo "操作成功!";

  23: // }else{

  24: //     die( "操作失败!".$mysqli->error);

  25: // }

  26:  

  27: // 查询多个结果集

  28: $sqls = "select * from userinfo where id>10;";

  29: $sqls .= "desc userinfo;";

  30: $sqls .= "select * from userinfo where uage>23;";

  31:  

  32: if($mysqli->multi_query($sqls))

  33: {

  34:     //循环读取每个表的数据

  35:     do{

  36:         if($result=$mysqli->store_result())

  37:         {

  38:             $tableStr="<table border='1' cellpadding='5'>";

  39:             //拼接表头信息

  40:             $tableStr.="<tr>";

  41:             while ($field=$result->fetch_field()) {

  42:                     $tableStr.="<th>".$field->name."</th>";

  43:             }

  44:             $tableStr.="</tr>";

  45:  

  46:             //拼接表内容信息

  47:             while ($row=$result->fetch_assoc()) {

  48:                 $tableStr.="<tr>";

  49:                 foreach ($row as $value) {

  50:                     $tableStr.="<td>$value</td>";

  51:                 }

  52:                 $tableStr.="</tr>";

  53:             }

  54:  

  55:             $tableStr.="</table>";

  56:  

  57:             //输出表数据

  58:             echo $tableStr;

  59:  

  60:             //释放结果集资源

  61:             $result->free();

  62:         }

  63:         if($mysqli->more_results()){

  64:             echo "<p>==================>>>>>></p>";

  65:         }

  66:     }while (@$mysqli->next_result());

  67: }

  68: else

  69: {

  70:     echo "操作出错:".$mysqli->error;

  71: }

  72:  

  73: //关闭连接

  74: $mysqli->close();

  75:  

  76: ?>