1, mysqli批量执行sql语句。基本语法:
$sqls=”sql1;sql2;………”
mysqli::multi_query($sqls);
同一个$sqls要么是增删改语句集合,要么是查询语句的集合,查询语句和增删改最好不要混合。应用示例如下:
① 操作数据库的代码:
<?php class mysqliMutiTool{ private $mysqli = null; private static $host = "10.252.158.217"; private static $user = "root"; private static $password = "521lhy"; private static $db = "test"; public function __construct(){ $this->mysqli = new MySQLi(self::$host,self::$user,self::$password,self::$db); if($this->mysqli->connect_error){ die("连接错误".$this->mysqli->connect_error); } // $this->mysqli->muti_query("set names utf-8"); } public function execute_query($sqls){ $res = $this->mysqli->multi_query($sqls); return $res; } public function getError(){ return $this->mysqli->error; } public function getMysqli(){ return $this->mysqli; } }
② 增删改操作
<?php require "mysqliMutiTool.class.php"; $mysqliMuti = new mysqliMutiTool(); $sqls = "insert into user1 (name,password,email,age) values(‘宋江‘,‘aaa‘,‘[email protected]‘,56);"; $sqls .= "insert into user1 (name,password,email,age) values(‘卢俊义‘,‘bbb‘,‘[email protected]‘,46);"; $sqls .= "insert into user1 (name,password,email,age) values(‘吴用‘,‘ccc‘,‘[email protected]‘,54);"; $sqls .= "update user1 set name = ‘吴用2‘ where id = 12;"; $sqls .= "delete from user1 where id = 15;"; $res = $mysqliMuti->execute_query($sqls); if($res){ echo "操作成功!"; }else{ echo "".$mysqliMuti->getError(); }
③ 查询操作
<?php require "mysqliMutiTool.class.php"; $mysqliMuti = new mysqliMutiTool(); $sqls = "select * from user1;"; $sqls .= "select * from words;"; $res = $mysqliMuti->execute_query($sqls); $mysqli = $mysqliMuti->getMysqli(); if($res){ do{ //从mysqli连接取出第一个结果集 $result = $mysqli->store_result(); //显示mysqli result对象 while($row=$result->fetch_row()){ foreach($row as $key=>$val){ echo "--$val"; } echo "<br/>"; } $result->free(); echo "<br/>*******************新的结果集*******************<br/>"; }while($mysqli->next_result()); } $mysqli->close();
时间: 2024-10-04 08:28:24