php+mysqli批量查詢多張表數(shù)據(jù)的方法

字號:


    這篇文章主要介紹了php+mysqli批量查詢多張表數(shù)據(jù)的方法,涉及multi_query、store_result及more_results等函數(shù)的使用技巧,需要的朋友可以參考下
    本文實(shí)例講述了php+mysqli批量查詢多張表數(shù)據(jù)的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
    注意這里使用到了兩個新的函數(shù)multi_query與store_result,具體代碼如下:
    代碼如下:
    <?php
    //1、創(chuàng)建數(shù)據(jù)庫連接對象
    $mysqli = new MySQLi("localhost","root","123456","liuyan");
    if($mysqli->connect_error){
    die($mysqli->connect_error);
    }
    $mysqli->query("set names 'GBK'");
    //2、查詢多個數(shù)據(jù)庫表
    $sqls = "select * from news limit 10,4;";
    $sqls .= "select * from user;";
    //3、執(zhí)行并處理結(jié)果
    if($res = $mysqli->multi_query($sqls)){
    //注意:與$mysqli->query()不同,這里返回的是布爾值
    do{
    $result = $mysqli->store_result();//這里才真正返回結(jié)果集的資源對象,失敗則返回false;
    while($row = $result->fetch_assoc()){
    foreach($row as $key=>$value){
    echo "--$value--";
    }
    echo "<hr>";
    }
    $result->free();
    if($mysqli->more_results()){//判斷是否還存在有結(jié)果集
    echo "----------查詢下一張表的數(shù)據(jù)---------------<br>";
    }
    }while($mysqli->next_result());//next_result() 返回 true 或false;
    }
    //4、關(guān)閉數(shù)據(jù)庫連接
    $mysqli->close();
    ?>
    希望本文所述對大家的php程序設(shè)計(jì)有所幫助。