Using PDO Objects in PHP 5 - Finding insertion IDs for database rows

As I pointed out in the section you just read, the PDO extension also offers a handy method, called "lastInsertId()," which is useful in those situations where it's necessary to find out the ID of the last-inserted database row.

The implementation of the method is very straightforward, as you can see in the example below:

 

/ example using the 'lastInsertId()' method (returns the ID of
last inserted row)
try{
            $dbh=new PDO('mysql:host=localhost;dbname=alejandro','user','password');
            $dbh->query("INSERT INTO users SET
name='Alejandro',address='Nowhere',email=
'[email protected]'");
            $insertId=$dbh->lastInsertId();
            echo 'ID of last-inserted row after executing SQL
statement is as following: '.$insertId;
} 
catch(PDOException $e) {
            echo 'Error : '.$e->getMessage();
            exit();
}
 Finding the ID of the last-inserted database row is an easy-to-perform task, thanks to the excellent functionality provided by the "lastInsertId()" method. Similar to the approach followed with previous examples, in this case I used the MySQL server to demonstrate how this method works, but as you saw earlier, this condition can be easily modified to work with a different database system.

As usual with many of my articles on PHP development, feel free to introduce your own modifications to all the hands-on examples shown here, so you can acquire a more robust grounding in how to use the most important features offered by the PDO extension. Fun is already guaranteed!

Final thoughts

In this first part of the series, I walked you through the key points of how to use the PDO extension that comes bundled with 5.1 and up. As was demonstrated by the hands-on examples included in this article, this library definitely makes working with multiple database systems a painless process.

Nonetheless, I have to admit that I'm only scratching the surface when it comes to exploring the numerous features offered by PHP Data Objects. So, considering the long way ahead of us, in the next tutorial I'm going to show you how to use this powerful PHP extension to manipulate results sets regardless of the database system you use.

Now that you've been warned, you won't want to miss it!

你可能感兴趣的:(sql,mysql,PHP,SQL Server,UP)