title: Mysql: Integrity constraint violation
body: <p>I am using <code>cleardb</code> for mysql database in <code>php</code>. And Situation is something like this:</p>
  
  <p>I am adding record in <code>beneficiary</code> table. and after adding that I am fetching <code>last_inserted _id</code>. And using this <code>id</code> to add payment method in <code>beneficiary_payment_info</code>. It works fine in most of the cases. But, sometimes I found below message in error log:</p>
  
  <blockquote>
    <p>Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (<code>cdb_85c337008c</code>.<code>beneficiary_payment_info</code>, CONSTRAINT <code>beneficiary_payment_info_ibfk_1</code> FOREIGN KEY (<code>ben_id</code>) REFERENCES <code>beneficiary</code> (<code>id</code>))'</p>
  </blockquote>
  
  <p>When I checked in database, I got this screenshots:</p>
  
  <p><img src="https://i.stack.imgur.com/DJfjV.png" alt="TABLE: beneficiary"></p>
  
  <p><img src="https://i.stack.imgur.com/b4d6c.png" alt="TABLE: beneficiary_payment_info"></p>
  
  <p>As you can see there is a id <code>6073</code> in first table but it's not in second table. I am getting above error just because of this. And there are 2 identical records(6073 and 6081) in first table because user has requested that page second time I guess.</p>
  
  <p>How can I solve this problem? Please guide me. Thanks.</p>
  
  <p><strong>EDIT (Reply from clearDB)</strong></p>
  
  <p>The best course to resolve this issue is to stop involving the auto_increment values.</p>
  
  <p>Rather than trying to guess or set them, you may be able to use a subquery, similar to the following style:</p>
  
  <pre><code>INSERT INTO CHILDREN (ParentID, FirstName, LastName)
  VALUES ((SELECT ID FROM PARENTS WHERE FirstName = 'John' AND LastName = 'Doe'),
  'Jane', 'Doe');
  </code></pre>