简体   繁体   中英

How to store results of multiple queries in different array variables

I need to get data from 2 different queries. I want to store them as 2 separate variables.

First I tried this:

// 1. Create a database connection
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME, DB_PORT);

if ($mysqli->connect_errno) {
    echo "No connection" ;
}
// 2. first query 
$query = "CALL sp1('2015-01-01', '2015-01-31');";
$result = $mysqli->query($query);

$var1 = array();
while($shop = $result->fetch_object()) {
    $var1[] = $shop;
}

echo '<pre>', print_r($var1), '</pre>';
$result->free();

// 3. second query 
$query = "CALL sp2('2015-01-01', '2015-01-31');";
$result = $mysqli->query($query);

$var2 = array();
while($shop = $result->fetch_object()) {
    $var2[] = $shop;
}

echo '<pre>', print_r($var2), '</pre>';

I get the data from 1st query however when php tries to fetch 2nd query I got this error:

Fatal error: Call to a member function fetch_object() on boolean

I read about multi_query but couldn't find anything about saving output from queries as separate variables.

Additional info: Even when I switch queries always the second one is not correct. I don't know how to load second query and what is happening to the previous one (gets deleted when I write:result->free?)

The solution was this little line:

$results->free();
// solution
$mysqli->next_result();

It seems that mysqli needs information that one query is finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM