I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
That statement works with a query like this:
But if I want to get the ID using this statement:
Pretty cool stuff for pretty cool people.
This is a short guide on how to get the ID of the last inserted row using PDO’s lastInsertId method. In case you didn’t already know, PDO is a popular PHP extension that provides an interface for accessing databases.
There are various reasons why you might need to retrieve the ID of the row that you just inserted. For example, if a user creates a new blog post, then you might want to redirect them to that blog post after it has been successfully inserted into the database.
For this example, I have created a simple MySQL table called posts. The structure of this table looks like so:
I’m using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted? It doesn’t work the way it looks now.
3 Answers 3
Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.