What role does the lastInsertId function play in PHP when inserting and querying data from a database?

The lastInsertId function in PHP is used to retrieve the auto-generated ID that was inserted into a database table with an auto-increment primary key during the last INSERT operation. This function is commonly used after inserting a new record into a database to obtain the ID of the newly inserted row. It is useful when you need to reference this ID in subsequent queries or operations.

// Inserting data into a table and retrieving the last inserted ID
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->execute();

$lastInsertedId = $pdo->lastInsertId();
echo "Last inserted ID: " . $lastInsertedId;