3

if I use this SQL:

UPDATE formulare SET EV_id=59, EV_status=5 WHERE EV_id=57 AND ID_uziv=12;SELECT LAST_INSERT_ID();

I will get 0 as last insert id. I'm using php mysqli_insert_id and here is said that:

The mysqli_insert_id() function returns the ID generated by a query 
on a table with a column having the AUTO_INCREMENT attribute. 
If the last query wasn't an INSERT or UPDATE statement 
or if the modified table does not have a column with the AUTO_INCREMENT attribute, 
this function will return zero. 

my table formualre has auto increment column, so I don't know wher the problem is

koubin
  • 579
  • 5
  • 9
  • 30

3 Answers3

8

LAST_INSERT_ID() won't work if no new auto increment value was created.

The solution is something like this:

UPDATE formulare
  SET EV_id=LAST_INSERT_ID(59),
    EV_status=5
  WHERE EV_id=57
    AND ID_uziv=12;
SELECT LAST_INSERT_ID();

Note: I guess, that EV_id is the auto_increment primary key.

Otherwise you should do a query like:

UPDATE formulare
  SET key_col = LAST_INSERT_ID(key_col),
    EV_id=59,
    EV_status=5
  WHERE EV_id=57
    AND ID_uziv=12;
SELECT LAST_INSERT_ID();
Regular Jo
  • 5,190
  • 3
  • 25
  • 47
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
  • 2
    It's also very helpful while doing `INSERT ... ON DUPLICATE KEY UPDATE` query to get `id` when row is updated. Even documentation mentions about this trick. :) – Jakub Matczak Aug 30 '13 at 12:03
2

From the documentation :

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

As your update didn't create a new record, it didn't generate any AUTO_INCREMENT value.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • ok, but why there is this `...If the last query wasn't an INSERT or UPDATE statement...` ? – koubin Aug 30 '13 at 10:45
  • 1
    This sentence is curious, but maybe the author was referring to [this kind of statement](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html). – Denys Séguret Aug 30 '13 at 11:14
1

UPDATE query updates the existing record, it doesn't return any new ID.

mysqli_insert_id retrieves the ID generated for an AUTO_INCREMENT column by the        
previous query (usually INSERT).

There was no INSERT query, that's the reason, you won't get any Id after executing UPDATE query.

For more info, refer mysql_insert_id

Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101