使用 PDO 准备好插入后获取最后一个插入 ID
我在一个新项目中使用 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;
}
I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自手册:
它应该类似于:
[编辑]更新文档链接
From the Manual:
It should be something like:
[EDIT] Update link to doc
来自 PHP 手册:
您还可以在 INSERT 语句中使用 RETURNING 并获取INSERT 结果类似于 SELECT 结果。
From the PHP manual:
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.
以前的答案不是很清楚(PDO 文档也是如此)
在 postgreSQL 中,当您使用
SERIAL
数据类型时会创建序列。因此序列名称将为
ingredients_id_seq
Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the
SERIAL
data type.So the sequence name will be
ingredients_id_seq