LoginSignup
12
14

More than 5 years have passed since last update.

MySQLで、INSERT後に、更新したデータのIDを取得する簡単な方法。PDOを利用して、last insert id 取得

Last updated at Posted at 2015-01-29

更新した後に、データのIDを取得したいとき、

My SQLで
mysql> SELECT LAST_INSERT_ID();

とやれば取得できます。

が、PDOを利用していれば、PDOの関数を使って、SQLを発行せずにlast insert idを取得することができます。

 $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

 $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");

try {
$dbh->beginTransaction();
$tmt->execute( array('user', 'user@example.com'));
print $dbh->lastInsertId();
$dbh->commit();
 }

 commitの後に$dbh->lastInsertId(); とやると、0しか返ってきません。
 トランザクションの間に、コミット前に、$dbh->lastInsertId(); の実行をして、取得します!簡単!

 実施する場所に要注意です。

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14