3

Using PHP and MySQL, I'm trying to get all the private chats involving the actual user. For that 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 initiating user of a chat room, I want to get the avatar and pseudo from the target user and if the actual user is the target user of the that room, I want to get the avatar and pseudo from the initiating user (whatever the case, I want the other member's avatar and pseudo).

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

Here is my query (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 plenty of questions around here regarding the "conditional where" but none of it solved my case. Thank you for your help.

1 Answer 1

3

Can't you 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
    )
) 
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly. I'm on this query since yesterday and as soon as I posted my question here, I managed to find the same query as yours which seems to work perfectly. It makes a lot of sense but from a beginner's perspective it's not necessarily that obvious. Thank you Arion. PS: How can I vote for you to thank you?
Good that you found it yourself. We all have been beginners. Glad to help. Maybe you can accept the answer then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.