当前位置:Gxlcms > 数据库问题 > mysqli的 mulit_query执行多条语句。

mysqli的 mulit_query执行多条语句。

时间:2021-07-01 10:21:17 帮助过:31人阅读

header(‘Content-type:text/html;Charset=utf-8‘); //error_reporting(E_ALL && E_NOTICE); define(‘DB_HOST‘, ‘127.0.0.1‘); define(‘DB_USER‘,‘root‘); define(‘DB_PWD‘,‘123456‘); define(‘DB_NAME‘,‘test‘); $start = microtime(true); //连接数据库 $_mysqli = new mysqli(DB_HOST,DB_USER,DB_PWD); if(mysqli_connect_errno()){ die(‘数据库连接错误!‘.mysqli_connect_error()); } //选择数据库,设置编码 $_mysqli->select_db(DB_NAME); $_mysqli->set_charset(‘utf8‘); $_sql = ‘‘; $_sql .= "select * from ecs_goods where goods_id = 5;"; $_sql .= "select * from ecs_goods where goods_id = 15;"; $_sql .= "select * from ecs_goods where goods_id = 25;"; $_sql .= "select * from ecs_goods where goods_id = 55;";//无该条记录 $_sql .= "select * from ecs_goods where goods_id = 35"; if($_mysqli->multi_query($_sql)){ do{ $_result = $_mysqli->store_result(); $_row = $_result->fetch_row(); echo $_row[0]; echo ‘<br />‘; $_result->free();//释放当前结果集 }while($_mysqli->more_results() && $_mysqli->next_result());//如果next_result 写在前面无法获得最后一条记录 }else{ echo(‘第一条语句出错!‘); exit(); } $_mysqli->close(); ?>

结果:
5
15
25

35

=====================================================================================

当然,以上例子每个sql语句的结果只有一条或者是没有记录,如果sql语句有多条记录。比如:

$_sql = ‘‘;
$_sql .= "select goods_id,goods_name,goods_sn from ecs_goods where goods_id in(1,2,32,4);";
$_sql .= "select goods_id,goods_name,goods_sn from ecs_goods where goods_id in(3,7,9);";
$_sql .= "select goods_id,goods_name,goods_sn from ecs_goods where goods_id = 25;";
$_sql .= "select goods_id,goods_name,goods_sn from ecs_goods where goods_id = 55;";//无该条记录
$_sql .= "select goods_id,goods_name,goods_sn from ecs_goods where goods_id = 35";

其中1,2语句都是多条记录。以下方式实现。

do{
        $_result = $_mysqli->store_result();
        while($_row = $_result->fetch_row()){
             echo($_row[0]);
             echo ‘<br />‘;
        }
        echo "<hr />";
        $_result->free();//释放当前结果集
    }while($_mysqli->more_results() && $_mysqli->next_result());//如果next_result 写在前面无法获得最后一条记录

结果:
技术分享

mysqli的 mulit_query执行多条语句。

标签:alt   where   star   mic   pwd   close   bool   notice   span   

人气教程排行