I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
$ArrayQuery->data_seek(0), or just use the already fetched result array.$ArrayQueryto be used in another while loop? I understand it's not exactly in best practice to use a situation like this; but i'm just finding out the kinks within MySQLI and seeing what would work; to what doesnt. Because if i move over tomysql_*functions; It would produce the expected output by using$ArrayQueryTwice in two different while loops.$ArrayQueryinternally keeps track of the index of the next row to be fetched. When your firstwhileloop ends,$ArrayQueryhas fetched all the results and this index is equal to the number of rows fetched. Your secondwhileloop then asks it to for each remaining result, but there are no further results to give, because the first loop took it all and the index says so. When you rewind$ArrayQueryusing Daryl Gill's answer (which is exactly what I suggested in my first comment), this internal index is reset and the second loop starts from the first row again.