title: PHP script to insert parsed email data while maintaining key relationships
body: <p>I'm currently in the process of finishing a PHP script which parses emails and inserts them into database tables structured like so -</p>
  
  <p><strong>Users table</strong></p>
  
  <ul>
  <li>userId - int - auto_increment - PK</li>
  <li>email - varchar</li>
  </ul>
  
  <p><strong>Emails table</strong></p>
  
  <ul>
  <li>emailId - int - auto_increment - PK</li>
  <li>userId - int - FK</li>
  <li>attachmentId - int - FK</li>
  <li>body - varchar</li>
  <li>subject - varchar</li>
  </ul>
  
  <p><strong>Attachments table</strong></p>
  
  <ul>
  <li>attachmentId - int - auto_increment - PK</li>
  <li>attachmentName - varchar</li>
  <li>fileType - varchar</li>
  <li>content - mediumblob</li>
  <li>code - varchar</li>
  </ul>
  
  <p>My problem is that once I have parsed the email, how do I ensure that my foreign key relationships are correct? My initial approach was just to perform: </p>
  
  <pre><code>INSERT INTO users (email) values ('$emailFrom');
  INSERT INTO emails (subject, body) values ('$subject', '$body');
  INSERT INTO attachments (attachmentName, fileType, content, code) values ('$attachmentName', '$fileType', '$content', '$code');
  </code></pre>
  
  <p>but then I realised that this won't deal with my FK relationships in the emails table. Is the best approach to perform each query individually, re-query for the generated Id then place the new Id in the related FK row? Sorry if I'm not being clear.</p>
  
  <p>Would there be any shortcomings in making this into one table and avoiding this problem?</p>