Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting insert id with insert PDO MySQL

Tags:

sql

php

pdo

Im getting to grips with the basics of PDO.

However Im trying to get the id of the inserted row, Im using:

$query = $system->db->prepare("INSERT INTO {$this->_table} (name,description) VALUES (:name,:description)");
$query->execute(array('name'=>$name,'description'=>$description));

The tutorials I have come across are regarding transactions, however I am not using transactions!

like image 715
pondpad Avatar asked Sep 18 '10 16:09

pondpad


People also ask

How can I get last INSERT ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How do I get the inserted row id in MySQL?

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

How do I get the last inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.


2 Answers

You're probably looking for lastInsertId. "Returns the ID of the last inserted row or sequence value".

$insertedId = $system->db->lastInsertId() ;
like image 99
Fanis Hatzidakis Avatar answered Sep 21 '22 01:09

Fanis Hatzidakis


Pay attention when using transactions.

If you call lastInsertedId after you call commit, lastInsertedId will return 0 instead of the id. Call lastInsertedId right after execute, but before commit.

$this->db->beginTransaction();
$this->stmt->execute();
$id = $this->db->lastInsertId();
$this->db->commit();
like image 27
Daniel Miranda Avatar answered Sep 21 '22 01:09

Daniel Miranda