dsirr48088 2014-07-31 22:39
浏览 20

为什么我的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?

  • 写回答

1条回答 默认 最新

  • dsfdsf8888 2014-07-31 22:43
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。