开发者

zend framework get last insert id of multi row insert using execute

How would I get the last inserted ID using a 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 next insert id before an insert?

thanks


$lastId=$contactsTable->getAdapter()->lastInsertId();

This worked.


So, here is the full working code I'm using to create a multi-row insert, getting the rows added 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;


An alternate solution. Move off sql code from controllers and place them in models. That is what they are for.

If you are using models, you can given the name of table which has auto increment column, in class variable.

protected $_name="<table_name>"; 

Then in your model class method, you can get last insert id from

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


that code should work, but it will only get you the id of your last insert.

you can get the next autoincrement 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜