【问题标题】:how to select all rows in sql table when a condition is meet满足条件时如何选择sql表中的所有行
【发布时间】:2017-05-25 14:57:30
【问题描述】:

我有一张这样的桌子。

+----+---------+-----------+
| id | user_id | friend_id | 
+----+---------+-----------+
|  1 |     1   |    20     |
|  2 |     4   |    20     |
|  3 |     6   |    20     | 
+----+---------+-----------+

正在开发一个friend_list系统,但现在我被代码卡住了,问题是我想回显他们的friend_id等于20的所有user_id,但是当我运行我的代码时它只会回显第一个user_id,请我的代码有问题吗?有人应该为我提供帮助并修复它。

 if(isset($_SESSION['em'])){
     $eml = $_SESSION['em'];

     $sql = "select id from users where email='$eml'";
     $res = mysqli_query($conn,$sql);
     $row = mysqli_fetch_assoc($res);

     $id = $row['id'];

     $sql_friend_list = "select user_id from friend where friend_id='$id'";
     $res_friend_list = mysqli_query($conn,$sql_friend_list);
     $row_friend_list = mysqli_fetch_assoc($res_friend_list);
      $fid = $row_friend_list['user_id'];

      echo $fid;
}

所以现在用户登录并且用户 id 等于 t0 20 然后代码检查登录用户的 id 是否等于friend_id 20。

【问题讨论】:

  • 你的选择没问题,问题是你必须从所有记录中循环也许this帮助

标签: php sql


【解决方案1】:

使用循环遍历关联数组。将最后三行代码替换为:

while($row = mysqli_fetch_assoc($res_friend_list)){
      echo $row['user_id'];
}

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    试试

    if(isset($_SESSION['em'])){
        $eml = $_SESSION['em'];
    
        $sql = "select id from users where email='$eml'";
        $res = mysqli_query($conn,$sql);
        $row = mysqli_fetch_assoc($res);
    
        $id = $row['id'];
    
        $sql_friend_list = "select user_id from friend where friend_id='$id'";
        $res_friend_list = mysqli_query($conn,$sql_friend_list);
        while($row = mysqli_fetch_assoc($res_friend_list){
            $fid = $row['user_id'];
            echo $fid;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2021-11-04
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多