doupafu6980 2015-04-22 18:35
浏览 87

在while循环中计算行数

I am trying to while loop information into a SELECT statement, then COUNT the results. I have tried at least 10 different "solutions" and none works. I only get 0, 1, or nothing. Here's my most recent attempt:

$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);

while ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC)) {

    $movie = $row35['movie'];

    $query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
    $result36 = $db->query($query36);
    $row36->fetchObject;

    $similar = $row36['similar'];

    echo $similar;

}
  • 写回答

3条回答 默认 最新

  • doujiu8826 2015-04-22 18:51
    关注

    If all you are looking to do is count the number of times your loop is run per script execution, then it is fairly simple to do. See below:

    $count = 0;
    
    while($row35 = $result35->fetch(PDO::FETCH_ASSOC)){
        //Do all your loop stuff.
        $count++;
    }
    
    var_dump($count);
    

    Important to note that your $count variable needs to be declared outside of your loop.

    Also you either need to use fetchAll with a foreach loop, or use fetch with a while loop, but don't mix them.

    Also a tip on good practice. Try to avoid as much as possible executing any kind of database querying with a loop, you can run into serious performance issues down the line as your loops get bigger.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败