gpt4 book ai didi

php - 使用 PDO 准备好插入后获取最后一个插入 ID

转载 作者:行者123 更新时间:2023-11-29 20:21:40 24 4
gpt4 key购买 nike

我在一个新项目中使用 PHP PDO 和 PostgreSQL。

给定以下函数,如何返回刚刚插入的行的 id?它并不像现在这样工作。

function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');

$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();

$id = $db->lastInsertId();
return $id;
}

最佳答案

来自Manual :

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

应该是这样的:

return $db->lastInsertId('yourIdColumn');

[编辑]更新文档链接

关于php - 使用 PDO 准备好插入后获取最后一个插入 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com