如何使用单个预处理语句获得刚刚插入的行的id ?


How do I get the id of the row I just inserted using a single prepared statement?

我以以下方式插入一行:

require("localhost_credentials.php");
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
$q_title = $fixed_title;
$q_tags = $_POST['tag_input'];
$q_mod = "n";
$q_t_create = date("m/d/Y @ G:i:s");
$q_t_modified = date("m/d/Y @ G:i:s");
$querystr  = "INSERT INTO mytable (title, tags, moderator, time_created, time_last_modified) ";
$querystr .= "VALUES (?, ?, ?, ?, ?);";
$statement = $conn->prepare($querystr);
$statement->bind_param("sssss", $q_title, $q_tags, $q_mod, $q_t_create, $q_t_modified);
$statement->execute();

我想获得我刚刚插入的行id,而不必进行第二次查询。我在SO上看到过一些这样做的方法,但是每次都有关于应该和不应该这样做的争论,我有点困惑。

使用预处理语句,如何使用一个查询获得新插入行的id ?

只要不执行多重插入,就可以使用

$conn->insert_id

当从该连接创建的语句执行INSERT查询时自动填充。

你可以这样写:

$last_id = $statement->insert_id($conn);

这将返回最后插入的行id。