dongwo6477 2011-04-03 14:48
浏览 136
已采纳

php count函数没有在mysql_fetch_assoc上显示正确的计数

I have got data from mysql_fetch_assoc stored in to an array using this command

if(mysql_num_rows($data) > 1){
                while($row = mysql_fetch_assoc($data)){
                    $ndata[] = $row;
                }
            } else {
                $ndata = mysql_fetch_assoc($data);
            }

Now when I use count on $ndata, it retuns 1; although it is empty.

When I run mysql_num_rows on the returned data it retuns 0 rows. But when I convert the data to $ndata and then run count on that it returns 1. I want it to return the number of rows.

Thanks

Can someone please explain why is there a problem and how to fix it?

  • 写回答

4条回答 默认 最新

  • dpjjmo3079 2011-04-03 14:51
    关注

    Your logic is wrong: you don't test for the case that mysql_num_rows($data) == 0. If this is the case, your code executes the same path as when the number of rows is 1 ($ndata = mysql_fetch_assoc($data);). But there are no more rows to return (there are no rows at all), so mysql_fetch_assoc returns false. And count(false) returns 1, because that's how count works.

    Do it this way:

    $rows = mysql_num_rows($data);
    if($rows == 0) {
        return null;
    }
    else if($rows == 1){
        $ndata = mysql_fetch_assoc($data);
    } else {
        while($row = mysql_fetch_assoc($data)){
            $ndata[] = $row;
        }
    }
    

    You can either return null or array() in the first if branch; these are the only two values for which count returns 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮