Mysql query and where where clause

Using PHP and MySQL, I am trying to get all the private chats with an actual user. To do this, I have a table called "rooms" (id, id_initiate_user, id_target_user) and another one called "users" (id_pseudo, avatar). If the actual user is the initiator of the chat, I want to get the avatar and pseudo from the target user, and if the actual user is the target user of this room, I want to get the avatar and pseudo from the initiating user (I want a different participant avatar and pseudo anyway).

I think I need a condition in my query, but I really don't know how to manage it (googled all day).

Here is my request (the logic is there, but the syntax is obviously wrong:

$user_id=$_SESSION['user_id'];

$res = @mysql_query("
SELECT rooms.id, rooms.id_initiate_user, rooms.id_target_user, rooms.pv, users.id, users.pseudo, users.avatar 
FROM rooms, users 
WHERE 
(
    (rooms.id_initiate_user='$user_id' OR rooms.id_target_user='$user_id') 
    AND  
    (
        IF (rooms.id_initiate_user='$user_id')
        THEN rooms.id_target_user=users.id
        ELSE rooms.id_initiate_user=users.id;
        END IF;
    )
) ORDER BY rooms.id ASC");

      

I read a lot of questions here regarding "conditional" but none of them solved my case. Thank you for your help.

+3


source to share


1 answer


You cannot do something like this:



WHERE 
(
    (
        rooms.id_initiate_user='$user_id'
        AND rooms.id_target_user=users.id
    )
    OR
    (
        rooms.id_target_user='$user_id'
        AND rooms.id_initiate_user=users.id
    )
) 

      

+3


source







All Articles