Hello,

i convert my module into Drupal 7, to test it in the alpha-2-version and i wonder if db_last_insert_id() still works, because at http://drupal.org/node/224333#dbtng there ist this part:

// Drupal 6
db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id();

// Drupal 7
$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();

I use it this way to generate neutral Teams:

    $lastid = db_last_insert_id('team','team_id');
    $nextid=$lastid+1;
    db_query('insert into {team} (team_name)values("%s")','Team'.$nextid);

Of course i have to convert the whole db_query thing(which is quite a lot). But what about the db_last_insert_id?

Comments

newbie888’s picture

db_last_insert_id() is not in D7.

MaWe4585’s picture

so need i to make an own workaround or is there something that i can use instead?

newbie888’s picture

InsertQuery::execute() returns last_insert_id.

MaWe4585’s picture

but i need the last id before the insert, because the insert itself contains the teamname..
although, i could make an update after the insert to change the name..

newbie888’s picture

fetch "select last_insert_id()".

AlexisWilke’s picture

That last one will probably not work with PostgreSQL...

vikramy’s picture

Check this out..

http://drupal.org/node/310079

$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();

So $id now contains last insert id. I believe after reading that. .Haven't looked into yet but will try out some examples later today and see. But this may be a good start..

GloolsGuan’s picture

Yes, but if you executed entity_load or what ever other functions, It is hards for you to get the last insert id. and Database::connection()->lastInsertId(); also can't return the currect insert_id value.

ignaciogutierrez’s picture

execute method, returns the last insert ID of the query, if one exists. So you just need:

$lastId = db_insert($table)->fields($data)->execute();

Saludos desde México

ibullock’s picture

If you still want to use db_query this works:

$lastid = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));

Ian Bullock