title: Mysqli multi_query
body: <p>I have two very similar scripts – one scheduled script, the other triggered by loading a PHP page – that download and parse email, then insert the various information I need into 3 tables. A simplified version of the query I had been using is:</p>
  
  <pre><code>INSERT INTO mailids () VALUES ();  
  SET @mysql_mid = LAST_INSERT_ID();  
  INSERT INTO mail (  
      mail_mid,   
      mail_owner_id,   
      mail_recipient,   
      mail_sender,   
      mail_subject,   
      mail_sent_date   
  ) VALUES (  
      @mysql_mid,   
      '$userId',   
      '$recipient',   
      '$sender',   
      '$subject',  
      FROM_UNIXTIME('$sentDate')  
  );  
  SET @mysql_mail_id = LAST_INSERT_ID();  
  INSERT INTO mail_body (  
      mail_id,  
      mail_body  
  ) VALUES (  
      @mysql_mail_id,  
      '$body'  
  );  
  UPDATE mailids SET mid_rec_ids = @mysql_mail_id WHERE mid_id = @mysql_mid;  
  </code></pre>
  
  <p>This worked just fine unless both scripts run at the same time, in which case both insert the email into the database, resulting in a duplicate entry.</p>
  
  <p>What I was hoping to do was add a SELECT statement to the beginning of my multi_query followed by an IF statement (which I have no experience with) that would only execute the above query if the email didn't already exist. In other words:</p>
  
  <pre><code>SELECT COUNT(*) AS mail_count FROM mail WHERE mail_owner_id = '$user_id AND mail_recipient = '$recipient' AND mail_sender = '$sender' AND mail_subject = '$subject' AND mail_sent_date = '$sent_date';
  
  IF mail_count &lt; 1  
  THEN   
      (INSERT ABOVE QUERY HERE)  
  END IF
  </code></pre>
  
  <p>Nothing I have tried has worked. I've tried setting a variable (@mail_count), using WHERE NOT EXISTS (which, for some reason, inserts a number of records equal to all records with my user_id) and about 100 other things I don't remember offhand. I considered going with PDO, but the rest of the project is mysqli and I am afraid of the learning curve of PDO in this project timeline.</p>
  
  <p>Can anyone help?</p>