我正在使用 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 给我最后插入的 ID?
- 在同一页上没有使用相同的 stmt 完成其他插入操作..*
更新:
根据 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
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement. In practice, it appears that the first insertion ID is returned. If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.
关于php - 在 mysqli 准备语句过程样式中获取最后插入的 id 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226740/