为什么我的foreach循环不能按预期工作?

I'm pretty new to PHP development, but I'd like to think I'm picking it up at a rapid pace, but I hit a bit of a problem when I moved from XAMPP to a real host. I'm trying to do something like this.

$cast_list = mysqli_query($dblink, $sql);
foreach ($cast_list as $role)
{
    echo "<tr><td width='50%'>".$role['appeared_as']."</td>";
}

It works on XAMPP which I have installed on my home PC, but it does not work on the hosting I've arranged to test with. The actual query is working perfectly, so that's not the problem. I can see the correct results in PHPMyAdmin, on XAMPP and when I change the code as follows.

$cast_list = mysqli_query($dblink, $sql);
$y = mysqli_num_rows($cast_list);
for ($x = 0; $x <$y; $x++)
{
    $role = mysqli_fetch_assoc($cast_list);
    echo "<tr><td width='50%'>".$role['appeared_as']."</td>";
}

The second code block will produce the desired effect. The first code block will apparently iterate 5 times, but will not contain any meaningful data. In fact a var_dump($role) for the first code block reveals that it is NULL.

I can just adapt to this if need be, but maybe there's a logical reason why foreach isn't working properly for me?

mysqli_query() doesn't return an array or array object that you can use with foreach(). The return type of mysqli_query() is a resource. You fetch from it in a loop, like your second solution.

It's simpler to use while() instead of for():

$cast_list = mysqli_query($dblink, $sql);
while ($role = mysqli_fetch_assoc($cast_list)) {
    echo "<tr><td width='50%'>".$role['appeared_as']."</td>";
}

The loop will terminate automatically when the row fetched is NULL at the end of the result set. You don't need to know the number of rows before the loop.


Re your comment:

After looking up some facts, I have to admit that my answer above isn't fully true. Or isn't true for some versions of PHP.

In PHP 5.4, a mysqli_result resource added Iterator functionality, you actually can use it in a foreach(). But your host apparently uses an older version of PHP.

The best practice is to develop on the same version of all software that you will deploy to, so you aren't caught by this sort of surprise.