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

后端 未结 16 2325
温柔的废话
温柔的废话 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:28

    It's sad not to see any answers with an example.

    Using Mysqli::$insert_id:

    $sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
    $mysqli->query($sql);
    $last_inserted_id=$mysqli->insert_id; // returns last ID
    

    Using PDO::lastInsertId:

    $sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
    $database->query($sql);
    $last_inserted_id=$database->lastInsertId(); // returns last ID
    

提交回复
热议问题