title: mysql insert into database only if user exists in datatabase?
body: <p>hi im looking for a way to implement a condition either in php or mysql that carry's out the below mysql query only if the 'from_user_id' exists in the database? </p>
  
  <p>i have table called ptb_users that stores all the user id's, the other table that the below query inserts content into is ptb_wallposts.</p>
  
  <p>users can write on other users walls, but before a user can write on a users wall/before the insert query runs i want the condition to cross reference with ptb_users to make sure the user sending the message/the from_user_id exists. so if user 1 is logged in and wants to send a message to user 2s wall then it first checks that the from_user_id matches the user_id in ptb_users.</p>
  
  <p>so for instance i dont want people to sql inject data into the database by being able to have a from_user_id of 0, it must be matching with a user_id in the database or display and error message.</p>
  
  <p>Can someone please advice me how i might do this. thanks. </p>
  
  <p>my ptb_wallposts table looks like this</p>
  
  <pre><code>id   |     from_user_id   |  to_user_id  |  content
  
  1               2                3            hello
  </code></pre>
  
  <p>my ptb_users table looks like this:</p>
  
  <pre><code>id   |     user_id   |  
  
  1             2            
  </code></pre>
  
  <p>mysql query:</p>
  
  <pre><code>$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
              mysql_query($sql, $connection);
  </code></pre>