Reputation: 601
I'm trying to fetch data and display it via foreach loop but it's not working giving argument error but when i try this with while loop it's work fine. so my question is that why i cannot fetch data using mysqli_fetch_array
with foreach why it's only possible with while loop
// While
while($row = mysqli_fetch_row($result))
{
var_dump($row); echo "<hr />";
}
// Foreach
foreach(mysqli_fetch_array($result) as $row)
{
var_dump($row); echo "<hr />";
}
Upvotes: 0
Views: 457
Reputation: 316
You can't use foreach for mysqli_fetch_array directly. Foreach is a loop using for an exist array, to loop through each its item
You can use like below
$result = array();
while($row = mysqli_fetch_array($result)) {
$result[] = $row;
}
foreach($result as $row) {
var_dump($row);
echo "<hr />";
}
Upvotes: 1
Reputation: 54841
Because mysqli_fetch_array
as comes from it's name - fetches one row of your result as array.
So, foreach(mysqli_fetch_array($result) as $row)
means
Fetch one row and iterate over this row.
While while($row = mysqli_fetch_row($result))
means
Do fetching rows until there's nothing to fetch. And when there's nothing to fetch
while
-condition isfalse
and the loop breaks.
Info about while
-loop and foreach
-loop
Upvotes: 0