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;

また、挿入の前に次の挿入 ID を取得する方法が ZF にありますか?

ありがとう

4

4 に答える 4

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

これはうまくいきました。

于 2010-01-25T14:12:00.010 に答える
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;
于 2010-01-19T15:05:50.920 に答える
0

そのコードは機能するはずですが、最後の挿入の ID しか取得できません。

次の mysql クエリで次の自動インクリメントを取得できます。

SELECT Auto_increment FROM information_schema.tables WHERE TABLE_SCHEMA = 'your_db_name' AND TABLE_NAME='the_table_you_want';
于 2010-01-19T14:49:12.283 に答える