1

I am trying to create a simple PHP MySQL driven message client.

So far I have two tables:

users which holds information about each person registered on the site. userID, firstName, lastName etc.

mail which contains a MessageID, fromUserID, toUserID, messageSubject, messageBody , dateSent etc.

Users can register and then log in. Once they are logged in they can view their 'inbox'.

What I am trying to figure out is how to list all the messages, and a preview for each message saying who it is from. Obviously I can get the fromUserID field from the mail table but that doesn't mean anything to the user, it is just a number, I want to use the userID and query the users table and pull from that the sender's first and last name.

I know I can use JOIN but I am not sure how to go about it, or can I use a sub query? What is better?

Any suggestions are very welcome.

2 Answers 2

2

You're going to want to join the users table, something like:

SELECT m.*, u.*
FROM mail m
  LEFT JOIN users u ON u.id = m.fromUserID
WHERE m.toUserID == 'LoggedInUserId'
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried this, only changing the u.id to u.userID and it threw an error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '== '1001'' at line 1. does it have to be ==? Or could it be LIKE?
Excellent. Joins are nearly always going to be faster than subqueries.
Just a detail: m.toUserID == 'LoggedInUserId' should be m.toUserID = 'LoggedInUserId' (note there's only one =).
0

Keep the userid in session when you validate the user. then you can get the data using the below query. select mail.* from mail m,users u where u.user_id=m.to_user_id and u.user_id=logged in userid

2 Comments

I'm not sure if I understand your answer correctly, but I think it is not what I was after. I want to get the details of the sender, not of the person who is logged in.
I think you din't get me, we need to get not only sender infor but also messages from them. we pull the messages based on to_userid and he is nothing but the person logged in. I think I am clear this time.

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.