title: IM Chat System in PHP and MYSQL?
body: <p>hi i am trying to setup an IM Chat system on my site so users can go onto a users profile and message them.</p>
  
  <p>so far, what i have is user 1 can message user 2 and both user 1 and user 2 can see the chat in that box window.</p>
  
  <p>my database looks like this:</p>
  
  <pre><code>id  |  to_user_id  | from_user_id  |  date_added  | content
  1           2              1            10/01/12     hello
  </code></pre>
  
  <p>my mysql insert looks like this:</p>
  
  <pre><code>$sql = "INSERT INTO ptb_chats (id, to_user_id, from_user_id,  content) VALUES (NULL, '".$profile_id."', '".$_SESSION['user_id']."', '".$chat_area."');";
              mysql_query($sql, $connection);
  </code></pre>
  
  <p>$profile_id stores what profile the user is on, so it knows which user to send the message to, however the user who receieves the message will also be on their profile because this is where the chat window is located.</p>
  
  <p>So now this causes a problem because user 1 will go onto user 2's profile and user 1 will type in a message. user 2 will recieve this message but if user 2 tries to reply to user 1, then because user 2 is replying from their profile the to_user_id in the database stores their $profile_id </p>
  
  <p>so the message that user 2 is sending back to user 1 isn't being delivered to user 1 it is being delivered to user 2. to_user_id is being set to the profile that user is on. </p>
  
  <p>I need a way to store the from_user_id from the previous message and on reply insert that as a value for to_user_id?</p>
  
  <p>i hope this makes sense. would appreciate any help thanks.</p>