mysql union select

I have a social network, I am writing a part of adding personal messages, I want to show both my sent and received messages at the same time, there is a problem with select

$query = "SELECT * FROM messages WHERE from_user_id = '".$_SESSION['user_id']."' to_user_id = '".$id."' ORDER BY id DESC 
            UNOIN SELECT * FROM messages WHERE from_user_id = '".$id."' to_user_id = '".$_SESSION['user_id']."' ORDER BY id DESC";
        $result = mysql_query($query);

What’s wrong here?


Answer 1, authority 100%

$query = "
  SELECT 
    msg.*, 
    CASE WHEN msg.from_user_id='".$_SESSION['user_id']."' THEN 1 ELSE 0 END AS recieved
  FROM messages AS msg 
  WHERE 
    msg.from_user_id='".$_SESSION['user_id']."'
    OR msg.to_user_id='".$_SESSION['user_id']."' 
  ORDER BY recieved, id DESC;
";

To explain: we select all messages related to the user + status (received, 1=incoming, 0=outgoing) and order first by “incoming”, then by id. If you just need everything without blocking, remove recieved from ORDER BY.

$res = mysql_query($query);
while ($msg = mysql_fetch_object($res)) {
  echo '<div class="msg">'.($msg->recieved ? '' : '').'<br /><b>'.$msg->title.'</b><br />'.$msg->content.'</div>';
  }

Somehow)

If the messages are for two users (sent to someone, received from someone), the WHERE block

$query = " ...
  WHERE
    (msg.from_user_id='".$_SESSION['user_id']."' AND msg.to_user_id='".$id."')
    OR (msg.to_user_id='".$_SESSION['user_id']."' AND msg.from_user_id='".$id."')
  ...
";

The rest is the same.