0

I have a problem with creating an inbox System. What i'm trying to do is in "ViewMessages.php" I am trying to pull information from a MYSQL Table to show messages.

My First Statement is:

    $MessageQuery = mysql_query("SELECT * FROM messages WHERE ToUName='$ToUName' AND FromUName='$FromUName'");

But I realised a flaw, it will only show messages sent 1 way. I Tried something like:

    $MessageQuery = mysql_query("SELECT * FROM messages WHERE ToUName='$ToUName' AND FromUName='$FromUName' OR FromUName='$ToUName' AND ToUName='$FromUName'");

This failed. Can anyone shed some light to show both messages from both parties?

Mike Causer
  • 8,196
  • 2
  • 43
  • 63
Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
  • 1
    SQL table structure, or it didn't happen. – moonwave99 Nov 05 '12 at 14:49
  • 2
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). Don't write new code with `mysql_*`. – Quentin Nov 05 '12 at 14:50

4 Answers4

3

How about union?

$MessageQuery = mysql_query("(SELECT * FROM messages WHERE ToUName='$ToUName' AND FromUName='$FromUName') UNION (SELECT * FROM messages WHERE FromUName='$ToUName' AND ToUName='$FromUName')");

Note: If you need messages in any particular order, you can use ORDER BY at the end of the query, hoping you have something like message_id or timestamp attached to each.

Arjun Abhynav
  • 543
  • 4
  • 15
1

You have boolean operators mixed up, try put some () into that.. (a AND b) OR (c AND d).

Also what you'd acomplish is getting all messages between you and the one other contact. Are you aware of that?

marianboda
  • 771
  • 6
  • 14
1
SELECT * 
FROM messages
WHERE '$ToUName' in (ToUName, FromUName)
OR '$FromUName' in (ToUName, FromUName)

or if you prefer columns listed first in your query

SELECT * 
FROM messages
WHERE ToUName in ('$ToUName', '$FromUName')
OR FromUName in ('$ToUName', '$FromUName')
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • You have mentioned the PHP $variable in the column place. – Arjun Abhynav Nov 05 '12 at 14:54
  • I have just tried this method, i'm using $_GET to get the information for the to and from, and if i modified ToUName to "testing" and kept the FromUName, it returned the results from the old variables. – Daryl Gill Nov 05 '12 at 15:00
  • SELECT * FROM messages WHERE ToUName in ('$ToUName', '$FromUName') AND FromUName in ('$ToUName', '$FromUName') just modified to that and it works. Thankyou – Daryl Gill Nov 05 '12 at 15:06
0

Try This:

$MessageQuery = mysql_query("SELECT * FROM messages WHERE ToUName='$ToUName' || FromUName='$FromUName'");

Vikas Umrao
  • 2,800
  • 1
  • 15
  • 23