简体   繁体   English

使用 PDO 在准备好插入后获取最后一个插入 id

[英]Get last insert id after a prepared insert with PDO

I'm using PHP PDO with PostgreSQL for a new project.我在一个新项目中使用 PHP PDO 和 PostgreSQL。

Given the following function, how can I return the id of the row just inserted?给定以下函数,如何返回刚刚插入的行的 id? 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;
}

From the Manual :手册

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.返回最后插入行的 ID,或序列对象的最后一个值,具体取决于底层驱动程序。 For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.例如,PDO_PGSQL() 要求您为 name 参数指定序列对象的名称。

It should be something like:它应该是这样的:

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

[EDIT] Update link to doc [编辑] 更新文档链接

From the PHP manual :从 PHP手册

For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.例如,PDO_PGSQL() 要求您为 name 参数指定序列对象的名称。

You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.您还可以在 INSERT 语句中使用RETURNING并像 SELECT 结果一样获取 INSERT 结果。

Previous answers are not very clear (PDO doc too)以前的答案不是很清楚(PDO 文档也是如此)

In postgreSQL, sequences are created when you are using the SERIAL data type.在 postgreSQL 中,序列是在您使用SERIAL数据类型时创建的。

CREATE TABLE ingredients (
  id         SERIAL PRIMARY KEY,
  name       varchar(255) NOT NULL,
);

So the sequence name will be ingredients_id_seq所以序列名称将是ingredients_id_seq

$db->lastInsertId('ingredients_id_seq');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM