使用 PHP、MySQLi 和 Prepared Statement,如何返回插入行的 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6556720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using PHP, MySQLi and Prepared Statement, how I return the id of the inserted row?
提问by Renato Dinhani
I want retrieve the id of a inserted row in the database, but I don't know how to do this.
我想检索数据库中插入行的 id,但我不知道该怎么做。
I tried to return using the SQL clause RETURNING id
, but not works.
我尝试使用 SQL 子句返回RETURNING id
,但不起作用。
How I can return the id after the insertion of a row?
插入一行后如何返回id?
回答by Renato Dinhani
After calling the execute()
method on the PreparedStatement
, the id of the insert row will be in the insert_id
attribute. Only read it.
调用 上的execute()
方法后PreparedStatement
,插入行的 id 将在insert_id
属性中。只阅读它。
$pstm->execute();
$pstm->insert_id;
回答by Marco
$newid = mysqli_insert_id($mysqli_db);
$mysqli_db
is your mysqli database connection. As far as I know it shouldn't matter on which way ou inserted the row (prepared statement or direct INSERT INTO
). mysqli_insert_id()
should return the id of the last inserted row using this db connection.
$mysqli_db
是您的 mysqli 数据库连接。据我所知,插入行的方式(准备语句或直接INSERT INTO
)无关紧要。mysqli_insert_id()
应该使用此数据库连接返回最后插入的行的 ID。
The alternative is to make another query like SELECT LAST_INSERT_ID();
.
另一种方法是进行另一个查询,如SELECT LAST_INSERT_ID();
.
回答by JrBriones
This is incorrect, you need to use:
这是不正确的,您需要使用:
$stmt = $db->prepare("SQL Query");
$stmt->execute();
$id = $db->lastInsertId();