C Francis
C Francis

Reputation: 53

how to select all rows in sql table when a condition is meet

i have a table like this.

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

am developing a friend_list system,But now am stuck with code,the problem is that i want to echo all the user_id that their friend_id equal to 20,But when i run my code it will only echo the first user_id,please were am i going wrong with my code someone should help and fix it for me.

 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;
}

so now the user is login and that user id is equal t0 20 then the code check if the id of the logged in user is equal to friend_id which is 20.

Upvotes: 0

Views: 82

Answers (2)

Canh Nguyen
Canh Nguyen

Reputation: 333

try

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;
    }
}

Upvotes: 0

Haris
Haris

Reputation: 763

Use a loop to iterate through the associative array. Replace the last three lines of code with this:

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

I hope this would help.

Upvotes: 2

Related Questions