2

I've read a lot of questions and answers related to this topic, but I can't find anything that's working for me, so I could really use some help.

I am trying to make a simple private messaging system for my website. I have a table like this:

private messages: id, to_id, from_id, message, time_sent

I am now trying to show a list on my page with the different users a member interacted with, something like Facebook messages so every name should appear only once in the list.

This is what I have now which shows me every message that I as a user ($my_id) participate in:

SELECT * FROM private_messages WHERE (from_id = '$Sid' AND to_id = '$my_id') OR (from_id = '$my_id' AND to_id = '$Sid')  ORDER BY time_sent ASC

This query shows a distincted list, but only of the people that I received a message from:

SELECT DISTINCT(from_id) FROM private_messages WHERE to_id='$my_id' ORDER BY time_sent DESC

How should I rewrite this so it gives me a distinct list of every user that I interacted with (like a list of facebook messages)? I think I need to distinct on two columns, from_id and to_id, but how should I do it?

I know the questions sounds rather vague, but I really can't explain it any better. Thanks in advance!

1 Answer 1

3

Try this:

SELECT DISTINCT IF(from_id = '$my_id', to_id, from_id) AS other_id
FROM private_messages 
WHERE '$my_id' IN (to_id, from_id) 
ORDER BY time_sent DESC
Sign up to request clarification or add additional context in comments.

6 Comments

Isn't there missing a closing bracket? : SELECT DISTINCT(IF(from_id = '$my_id', to_id, from_id) AS other_id) FROM....
@TomK. Thanks for the remark. This was a typo. DISTINCT does not need any parentheses as it is not a function.
you're right, just saw that there was something missing ... you're welcome.
Thank you, this seems to give me two rows, which is what I need! Now I am trying to echo the rows based on the value of from_id and to_id. So after fetching the array, I do like this: if($row['from_id'] == $my_id) { echo xxxxx } elseif($row['to_id'] == $my_id) { echo xxxxxx }, but it's not working, it doesn't show any rows..
I tried that at first, but I was mistakenly using mysqli_fetch_array instead of mysqli_fetch_assoc. It works now, thanks for the help, you saved my day!
|

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.