Home  >  Q&A  >  body text

How to get last insert ID of MySQL table in PHP?

<p>I have a table into which new data is frequently inserted. I need to get the last ID of the table. How can I do this? </p> <p>Is it similar to <code>SELECT MAX(id) FROM table</code>? </p>
P粉504080992P粉504080992423 days ago515

reply all(2)I'll reply

  • P粉973899567

    P粉9738995672023-08-24 17:15:20

    There is a function that can know what the last id inserted in the current connection is

    mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
    $id = mysql_insert_id();

    Plus using max is a bad idea as it may cause problems if your code is used simultaneously in two different sessions. .

    The function is called mysql_insert_id

    reply
    0
  • P粉895187266

    P粉8951872662023-08-24 10:49:27

    If you are using PDO, use PDO::lastInsertId.

    If you are using Mysqli, please use mysqli::$insert_id .

    If you are still using Mysql:

    But if you must, use mysql_insert_id .

    reply
    0
  • Cancelreply