Lesson 6.7. Get last ID

Foreword

We will assume on this page the existence of a $db variable which contains the database connection parameters which is created in accordance with the code presented on the MySQL Connection in PHP page.

When writing or updating data in MySQL, it is very common to have to retrieve the identifier (primary key) of the last line modified or added. There is a PHP function dedicated in returning this identifier.

Syntax

The lastInsertId (); method returns the primary key of the last row inserted or modified.

$lastId = $db->lastInsertId();

This method can only be used with tables that contain an AUTO_INCREMENT field.

See also


Last update : 09/17/2022