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=
'alejandro@domain.com'");
            $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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值