Skip to content
PHP Logo

What is the correct syntax to retrieve the last inserted ID in a Postgresql database using PDO in PHP?

When inserting data into a Postgresql database using PDO in PHP, you may need to retrieve the last inserted ID for further operations. To achieve this, you can use the `lastInsertId()` method provided by PDO. This method returns the ID of the last inserted row in the database.

php
// Insert data into the database
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->execute(array(':value1' => $value1, ':value2' => $value2);

// Retrieve the last inserted ID
$lastId = $pdo->lastInsertId();
echo "Last inserted ID: " . $lastId;