The error from your first coding attempt comes because you are storing the boolean result of mysqli_multi_query()
as $test_result
and then trying to feed $test_result
to mysqli_fetch_assoc()
. You intend to send the query result to the fetching function but that isn't how it's done with multi_query -- this is an understandably confusing versus how mysqli_query()
works.
Here is a vital quote from the manual:
To retrieve the resultset from the first query you can use mysqli_use_result()
or mysqli_store_result()
. All subsequent query results can be processed using mysqli_more_results()
and mysqli_next_result()
.
...This quote also touches on the issue with your second posted attempt which is only checking mysqli_next_result($link)
. Explicitly following the manual's instructions means writing the following while
condition:
} while(mysqli_more_results($link) && mysqli_next_result($link));
The answer provided/selected by the OP is a workaround for not being able to find the solution. This whole $i
business should be removed; you don't see this type of work at any of the mysqli docs pages.
Of the queries that you are running, only one of them should have a record set.
CREATE TEMPORARY TABLE //returns true/false. *structural, no rows in this case.
INSERT //returns true/false. *mysqli_affected_rows if desired.
UPDATE //returns true/false. *mysqli_affected_rows if desired.
SELECT //returns record set. *max of 1 row in this case.
My proposed solution is:
if (mysqli_multi_query($link, $multi_test_query)) {
do {
if ($result = mysqli_store_result($link)) { // record set was generated for this query
$satirsayisi = mysqli_fetch_row($result)[0];
mysqli_free_result($result);
}
} while (mysqli_more_results($link) && mysqli_next_result($link));
}
if ($hata = mysqli_error($link)) {
echo "Error / hata: $hata"; // don't display error messages when site is public
} else {
echo "Number of lines / satır sayısı: $satirsayisi";
}
If there are any errors, $hata
will be echoed.
If your SELECT query was successful, $satirsayisi
will be your count value echoed to screen.
Additional advice/points:
Fetching From Single-Value-Result: using mysqli_fetch_row()[0]
gets the job done in one line; no while loop needed.
Looping mysqli_multi_query()
: Reference docs use DO WHILE
loops so that the loop is always entered on the first iteration, and the condition statement is checked at the end of each iteration.
If there are any errors with any of the queries, mysqli_multi_query
will cease executing subsequent queries -- this is how the function is designed to behave.