How do I get the last inserted ID of a MySQL table in PHP?

后端 未结 16 2478
温柔的废话
温柔的废话 2020-11-21 23:09

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

Is it similar to SELECT MAX(id) FROM

16条回答
  •  耶瑟儿~
    2020-11-21 23:45

    NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.

    The table:

    create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

    Now if you do:

    insert into xyz (name) values('one'),('two'),('three');

    The mysqli::insert_id will be 1 not 3.

    To get the correct value do:

    mysqli::insert_id + mysqli::affected_rows) - 1

    This has been document but it is a bit obscure.

提交回复
热议问题