Answers.Body: <p>You could do something like <code>CRM_Core_DAO::executeQuery("SELECT LAST_INSERT_ID()");</code>. If your needs are simple that seems like the easiest.</p>
  
  <p>Probably to do it "right", you would use <code>civix generate:entity</code>. See <a href="https://docs.civicrm.org/dev/en/latest/extensions/civix/#generate-entity" rel="noreferrer">https://docs.civicrm.org/dev/en/latest/extensions/civix/#generate-entity</a></p>
  
  <p>Then you could do things in an object-y way, like:</p>
  
  <p><code>
  $myclass = new MyClass();
  $myclass-&gt;field1 = 'foo';
  $myclass-&gt;field2 = 'bar';
  $myclass-&gt;save();
  // Then the inserted id is automatically in $myclass-&gt;id (assuming your auto_increment field is called 'id'
  </code></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-05-29T05:31:36.817Z
Answers.LastActivityDate: 2019-05-29T05:47:26.570Z
Answers.LastEditDate: 2019-05-29T05:47:26.570Z
Answers.UserDisplayName: Demerit
Body: <p>Within a new extension, in a form's postProcess function, I am inserting into a non-Civi table (separate mysql database/table). What is the proper way to execute a MySQL insert statement and retrieve the new id from that insert using CRM_Core_DAO?  I use executeQuery for selects, and can use it to run the insert as well, but not sure that's the best way and not sure how to get the id back.</p>
  
Tags: <extension><database>
Title: Insert and Get New ID in Extension
ThreadText: # Insert and Get New ID in Extension
  
  (Asked by: username_0 on 2019-05-28)
  
  Within a new extension, in a form's postProcess function, I am inserting into a non-Civi table (separate mysql database/table). What is the proper way to execute a MySQL insert statement and retrieve the new id from that insert using CRM\_Core\_DAO? I use executeQuery for selects, and can use it to run the insert as well, but not sure that's the best way and not sure how to get the id back.
  
  **Tags:** extension, database
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2019-05-29. Score: 5 | Accepted answer
  
  You could do something like `CRM_Core_DAO::executeQuery("SELECT LAST_INSERT_ID()");`. If your needs are simple that seems like the easiest.
  
  Probably to do it "right", you would use `civix generate:entity`. See <https://docs.civicrm.org/dev/en/latest/extensions/civix/#generate-entity>
  
  Then you could do things in an object-y way, like:
  
  `$myclass = new MyClass();
  $myclass->field1 = 'foo';
  $myclass->field2 = 'bar';
  $myclass->save();
  // Then the inserted id is automatically in $myclass->id (assuming your auto_increment field is called 'id'`
  
  
  ---
  
  