Zend框架使用execute获取多行插入的最后插入ID

5

如何使用多行插入获取最后插入的ID?以下是我的代码:

$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;

同时,ZF是否有一种方法可以在插入之前获取下一个插入id?

谢谢

4个回答

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

这个有效。


3

以下是我使用的完整工作代码,用于创建多行插入,获取添加的行和最后插入的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;

2

另一种解决方案是将sql代码从控制器中移出,并将其放置在模型中。这就是它们的用途。

如果您正在使用模型,可以在类变量中给出具有自动增量列的表的名称。

protected $_name="<table_name>"; 

然后在您的模型类方法中,您可以从中获取最后插入的id:

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

0

那段代码应该可以工作,但它只会给你最后插入的ID。

你可以使用这个MySQL查询语句来获取下一个自增值:

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

谢谢solomongaby。 它给了我这个错误: 致命错误:调用未定义的方法Zend_Db_Statement_Pdo :: lastInsertId()插入正常工作。它也很好地给了我添加的行数。奇怪! - EricP
我明白了!$lastId=$contactsTable->getAdapter()->lastInsertId(); 我还不知道为什么另一种方式不起作用。 - EricP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接