How would I go about this.

I have a database query that automaticaly generates an id using the auto increment feature of mysql.
When I insert something into this table I want to get the value for the id it just generated.

Hope this makes sense to anybody

Comments

kscheirer’s picture

you should think about using drupal's db_next_id() function. It lets
you simulate an auto_increment field on any database. In this case since you created the new ID yourself, you don't need to go back to the database to retrieve the value.

but if you're not concerned about using your code with any other database, you
can use mysql's built in LAST_INSERT_ID statement.

hope that helps,
-ks

jlab’s picture

I used the MySQL LAST_INSERT_ID() function. Works like a charm.

Thanks for the great tip. Much appreciated.

Artificial Intelligence is no match against Natural Stupidity

geshan’s picture

This might be a better Drupal specific solution: http://api.drupal.org/api/function/db_last_insert_id/6 - It says its thread safe :).

kpv’s picture

For D7

  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));

For more info see:
http://api.drupal.org/api/drupal/includes--database--database.inc/functi...
http://api.drupal.org/api/drupal/includes--database--database.inc/class/...

togbonna’s picture

How would you get the last_insert_id after a drupal_write_record(...) call in D7, since db_last_insert_id() is not supported???

www.icelark.com
Think.Act.Be
@togbonna
@icelark

alecspopa’s picture

The second parameter for drupal_write_record is a reference to the object that is being inserted and any values that are not provided in that will be populated after insert.
Here is the function documentation: api.drupal.org - drupal_write_record

togbonna’s picture

Cool! I'll see if it works as advertised.

Thanks.

www.icelark.com
Think.Act.Be
@togbonna
@icelark