LAST_INSERT_ID not working on UPDATE

半城伤御伤魂 提交于 2019-12-10 11:46:48

问题


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


回答1:


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();



回答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.




回答3:


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



来源:https://stackoverflow.com/questions/18530872/last-insert-id-not-working-on-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!