How to get my friend's ID?

I have such a table friends enter image description here

My unique ID 1

  1. The first stage is a list of all friends.

    SELECT * FROM friends WHERE friends.user_from = $id OR friends.user_to = $id;

We get 2, 4, 6

  1. The second stage is a list of all friends of my friend.

    SELECT * FROM friends WHERE friends.user_from IN (SELECT friends.user_to FROM friends WHERE friends.user_from = $id) OR friends.user_to IN (SELECT friends.user_from FROM friends WHERE friends.user_to = $id);

We get 2 3, 4 7

  1. The third stage is how to find out my friend's ID

Received 2 or 3, 4 or 7

  1. The fourth stage should be like this

    echo $row['user_from']. ' '.$row['user_to']. '. Мой друг: '.$row['friend'];
    2 3. Мой друг: 2
    4 7. Мой друг: 4


  • Is the error so incomprehensible that the text of the error cannot be copied here? - Mike
  • @Mike please Fatal error: Uncaught Error: Call to a member function rowCount () on C: \ xampp \ htdocs \ core \ friends.class.php: 179 Stack trace: # 0 C: \ xampp \ htdocs \ index. php (14): friends-> all ('1', 'news', '', 'true', '') # 1 {main} thrown in C: \ xampp \ htdocs \ core \ friends.class.php on line 179 - KYRAN
  • And by the way, that means "transfer to AS". AS is the alias designation for a field; it is impossible to transfer anything to it. And AS in this request is not needed anywhere, although, of course, it should not interfere - Mike
  • @Mike And how can I get friends.user_from and friends.user_to in IN() as a friend - KYRAN
  • But in the code you apply here, there is no call to the rowCount () function on which the error occurs. And the error itself says that after sending the request to the database you were not convinced that there were no errors in the request. And apparently they were. because it returned false. It is necessary to make a check for false and put the error output of the database (see an example in the descriptions of the functions of working with the database that you use, there is usually an example of checking for errors and displaying messages) - Mike

1 answer 1

For MySQL:

 select A.user_from, A.user_to, B.friend from friends A join ( select if(user_from=1,user_to,user_from) as friend from friends where user_from=1 or user_to=1 ) B on (A.user_from=B.friend or A.user_to=B.friend) and A.user_from!= 1 and A.user_to != 1 

For other DBMSs, if they do not support the IF() function, replace it with case when user_from=1 then user_to else user_from end .

  • thank you very much! - KYRAN