'Mysqli multi query error

I need to execute two or more queries at a time, fetch them one after another.

Then I need to bind param and bind result in each one of them.

I am trying this way but getting error.

$query="
SELECT 
`date`, `ip`, AVG(`value`)
FROM `stats`.`stats`    
WHERE `uid`=?
GROUP BY `date`, `ip`;
";

$query.="
SELECT 
`category`, `ip`, AVG(`value`)
FROM `stats`.`stats`    
WHERE `uid`=?
GROUP BY `category`, `ip`;
";

$prepare = mysqli_multi_query($connection, $query);
mysqli_stmt_bind_param($prepare, 'ss', $uid,$uid);
mysqli_stmt_execute($prepare) or trigger_error(mysqli_error($connection), E_USER_ERROR);

Then in html part I need to fetch result of these one after another

//fetch first query result
while (mysqli_stmt_fetch($prepare)):
mysqli_stmt_store_result($prepare);
mysqli_stmt_bind_result($prepare, $date,$ip,$value);
mysqli_free_result($result);
endwhile;

//fetch second query result
while (mysqli_next_result($prepare)):
while (mysqli_stmt_fetch($prepare));
mysqli_stmt_store_result($prepare);
mysqli_stmt_bind_result($prepare, $category,$ip,$value);
mysqli_free_result($result);
endwhile;

But its not working showing multiple errors.

 Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in
 Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in
 Fatal error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? GROUP BY `date`,`ip` ) ..

Please see and suggest any possible way to do this.

Thanks



Solution 1:[1]

I need to execute two or more queries at a time

You don't.

And, therefore, you should use just regular prepare/execute for your queries, running them one by one. A transaction could be added to boost speed and consistency

$data = [
    ['col1' => 'foo1', 'col2' => 'bar1'],
    ['col1' => 'foo2', 'col2' => 'bar2'],
];
// prepare SQL query once
$stmt = $mysqli->prepare("INSERT INTO table SET col1 = ?, col2 = ?");

$mysqli->begin_transaction();
// loop over the data array
foreach ($data as $row) {
    $stmt->bind_param("ss", $row['col1'], $row['col2']);
    $stmt->execute();
}
$mysqli->commit();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1