mysqli扩展库应用---批量执行sql语句
1, mysqli批量执行sql语句。基本语法:
$sqls=”sql1;sql2;………”
mysqli::multi_query($sqls);
同一个$sqls要么是增删改语句集合,要么是查询语句的集合,查询语句和增删改最好不要混合。应用示例如下:
① 操作数据库的代码:
<?php class mysqliMutiTool{ private $mysqli = null; private static $host = "127.0.0.1"; private static $user = "root"; private static $password = "123456"; 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; } public function closeConn(){ $this->mysqli->close(); } }
② 增删改操作
<?php require "mysqliMutiTool.class.php"; $mysqliMuti = new mysqliMutiTool(); $sqls = "insert into user1 (name,password,email,age) values('宋江','aaa','songjiang@126.com',56);"; $sqls .= "insert into user1 (name,password,email,age) values('卢俊义','bbb','lujunyi@126.com',46);"; $sqls .= "insert into user1 (name,password,email,age) values('吴用','ccc','wuyong@126.com',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(); } $mysqliMuti->closeConn();
③ 查询操作
<?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()); } $mysqliMuti->closeConn();