[英]Which is correct way to get last inserted id in mysqli prepared statements procedural style?
我正在使用mysqli預處理語句在這樣的表中插入記錄
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
mysqli_stmt_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) > 0){
//if insert is successful then get the insrted id.
}
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
並且想獲得最后插入的id,因為該表具有record_num字段,該字段是自動增量。
所以我的問題是我應該在函數內放置連接名稱或語句名稱。
即1)
echo mysqli_insert_id($link);
資料來源: http : //php.net/manual/en/mysqli.insert-id.php
2)
echo mysqli_stmt_insert_id($stmt);
資料來源: http : //php.net/manual/en/mysqli-stmt.insert-id.php
哪一個是正確的? $ stmt中哪一個會給我最后一個ins id?
更新:
根據http://php.net/manual/en/mysqli-stmt.insert-id.php的說明
我只做單插入,所以我想我可以使用
mysqli_stmt_insert_id($stmt)
但是在使用預處理語句進行多次插入時
echo mysqli_insert_id($link);
是最好的做法。
你應該用
mysqli_insert_id($link);
由於您在PHP手冊中提到了這一說明,因此我們提到了
mysqli_stmt_insert_id
應該注意的是,使用mysqli_stmt-> insert_id不會導致為每次執行准備好的insert語句返回唯一ID。 實際上,似乎返回了第一個插入ID。 如果您使用相同的預准備語句執行多個插入(一次調用mysqli_stmt :: prepare以及對給定語句多次調用mysqli_stmt :: execute()),並且需要為每個插入保留唯一ID,請使用mysqli_connection-> INSERT_ID。
對於程序語言,你需要使用下面的代碼,mysqli_insert_id($ link));
是的,正如你在1點提到的那樣。
正確是1) - 鏈接,如文件中所述:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.