哪种是在mysqli准备好的语句过程风格中获取最后插入的id的正确方法? [英] Which is correct way to get last inserted id in mysqli prepared statements procedural style?
问题描述
我正在使用mysqli准备的语句在这样的表中插入记录
i am using mysqli prepared statement to insert record in the table like this
$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字段,该字段是自动递增的.
and would like to get the last inserted id , as the table has record_num field which is auto increment .
所以我的问题是我应该在函数中放置连接名称还是语句名称.
so my question is should i place connection name or the statement name inside the function.
即 1)
echo mysqli_insert_id($link);
来源: http://php.net/manual/zh /mysqli.insert-id.php
2)
echo mysqli_stmt_insert_id($stmt);
来源: http://php.net/manual /en/mysqli-stmt.insert-id.php
哪个是正确的? 哪个会给我最后一个$ stmt插入的ID?
which one is correct ? which one will give me last insrted id by the $stmt ?
- 在同一页面上使用相同的stmt没有其他插入操作.*
更新:
根据 http://php.net/manual上的注释/en/mysqli-stmt.insert-id.php
我只做一次插入操作,所以我想我可以使用
I am doing only single insert so i guess i can use
mysqli_stmt_insert_id($stmt)
但是在使用
echo mysqli_insert_id($link);
是最佳实践.
推荐答案
您应该使用
mysqli_insert_id($link);
由于您在PHP手册中有此说明,因此我们将其引荐给我们
Because of this note on the PHP manual you referred us to
mysqli_stmt_insert_id
应该注意的是,使用mysqli_stmt-> insert_id不会导致每次执行准备好的插入语句时都返回唯一的ID.实际上,似乎返回了第一个插入ID.如果要使用相同的准备好的语句执行多个插入(对于给定的语句,一次调用mysqli_stmt :: prepare和多次调用mysqli_stmt :: execute()),并且需要为每个插入保留唯一的ID,请使用mysqli_connection-> 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.
这篇关于哪种是在mysqli准备好的语句过程风格中获取最后插入的id的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!