Zend framework gets the last insert id from a multi-line insert using execute

How do I get the last inserted id using multirow insert? Here is my code:

$sql='INSERT INTO t (col1, col2, col3) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9)'; // example
$stmt = $contactsTable->getAdapter()->prepare($sql);
$stmt->execute(); 
$rowsAdded=$stmt->rowCount(); // mysql_affected_rows
$lastId=$stmt->lastInsertId();
echo '<br>Last ID: '.$lastId;

Also, is there a method in ZF to get the following insert identifier before insertion?

thanks

+5
source share
4 answers
$lastId=$contactsTable->getAdapter()->lastInsertId();

It worked.

+10
source

So, here is the full working code that I use to create a multi-line insert, get the added rows and the last inserted id:

$contactsTable = new Contacts_Model_Contacts();
$sql='INSERT INTO t (col1, col2, col3) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9)'; // example
$stmt = $contactsTable->getAdapter()->prepare($sql);
$stmt->execute(); 
$rowsAdded=$stmt->rowCount(); // mysql_affected_rows
$lastId=$contactsTable->getAdapter()->lastInsertId(); // last inserted id
echo '<br>Last ID: '.$lastId;
+3
source

. sql . , .

, , , .

protected $_name="<table_name>"; 

$insertID= $this->getAdapter()->lastInsertId();
+2

, .

you can get the following auto-increment with this mysql query:

SELECT Auto_increment FROM information_schema.tables WHERE TABLE_SCHEMA = 'your_db_name' AND TABLE_NAME='the_table_you_want';
0
source

All Articles