I am trying to put the entire results set into an array as follows:
while($myres[]=$result->fetch_array(MYSQLI_ASSOC));
This works ok but if I have 5 rows returns in my results the array has 6 index the last being null. So it seems that my array is always one index too big.
I could use num_rows to loop the results but this requires me setting up my own counter and incrementing it, I like the shorthand efficiency of my line above but how to stop it populating the last index with a null set.
This is an alternative to me using fetch_all
which I discovered requires a special driver which not all php servers have installed.
I would just use multiple lines
$myres = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$myres[] = $row;
However, if you have to have it without the extra array assignment line
while ($row = $result->fetch_array(MYSQLI_ASSOC) && $myres[] = $row) {
but that is more or less the same.
The expression
while($myres[]=$result->fetch_array(MYSQLI_ASSOC));
does the following:
$result->fetch_array(MYSQLI_ASSOC)
$myres[]
, thereby appending an entry to the $myres
array $result->fetch_array(MYSQLI_ASSOC)
as a condition to the while
statement and determine whether the loop should be exited. Notice that appending an entry to the $myres
array happens before determining if the while
loop should be exited. This is where your extra row comes from.
You will not lose any efficiency by doing it the classical way:
while ($record = $result->fetch_array(MYSQLI_ASSOC)) {
$myres[] = $record;
}
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.