SQL查询一遍又一遍地返回相同的结果

时间:2016-08-29 17:23:29

标签: php mysql

我有一个查询搜索用户名以及用户是否跟踪它们。该结果显示在while循环中。在该循环中,我有另一个查询,将查看有多少人关注该用户。问题是它将显示所有结果的相同数字。它只运行查询一次左右。这是代码:

<?php 
    $req = $db->prepare("SELECT * FROM users, follows WHERE follows.userId = ?     AND follows.followerId = users.userId ORDER BY users.username");
              $req->execute(array($userId));
              while($data = $req->fetch()){

                ?>
                  <p>
                    <img src="files/useruploads/<?php echo $data['profilePic']; ?>" class="left" style="width: 30px; height: 30px; border-radius: 900px;" alt=""/>
                    <a href="<?php echo $data['username']; ?>/"><?php echo $data['username']; ?></a><br>
                    <?php
                    $followers = $db->prepare("SELECT *, COUNT(*) AS followers FROM follows WHERE follows.followerId = ?");
                    $followers->execute(array($data["userId"]));
                    if($date = $followers->fetch()){
                      $totFollowers = $date["followers"];
                    }
                    ?>
                    <span class="grey-text"><?php echo $totFollowers; ?></span>
                  </p>
                <?php
              }
              ?>

2 个答案:

答案 0 :(得分:0)

用您的内部查询替换代码:

using (var db = new DbEntity())
{
    var sqlStatement = new StringBuilder();

    sqlStatement.AppendFormat("SELECT * FROM TABLENAME WHERE ID = '{0}' ", id);

    var result = db.ExecuteStoreQuery<MyTableObject>(sqlStatement.ToString()).ToList();
}

预期结果应该到来。

答案 1 :(得分:-1)

假设查询字符串中没有错误。

尝试替换以下代码

if($date = $followers->fetch()){
                      $totFollowers = $date["followers"];
                    }

while($date = $followers->fetch()){
                      $totFollowers = $date["followers"];
                    }