Search code examples
phpmysqlsqlrowauto-increment

Get the AUTO_INCREMENT value after inserting a new row


How can I get the id that was just inserted for the current user if it is controlled by AUTO_INCREMENT?

(I need the Id for another use)

Note: some row can be deleted so MAX(id) is not an option.

Ex:

inserted row 2

inserted row 3

deleted row 3

inserted row 4 but MAX(id) returns 3..

Thank you very much!


Solution

  • With PDO:

    $db->lastInsertId(); // $db is the PDO object
    

    With MySQLi OOP:

    $db->insert_id; // $db is the MySQLi object
    

    With MySQLi procedural:

    mysqli_insert_id($db); // $db is the connection variable
    

    If you're using the old MySQL API, switch.