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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5057954/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:41:16  来源:igfitidea点击:

Get last insert id after a prepared insert with PDO

phppostgresqlpdoprepared-statement

提问by Psyche

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? It doesn't work the way it looks now.

给定以下函数,如何返回刚刚插入的行的 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;
}

回答by Alix Axel

From the 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.

返回最后插入行的 ID,或序列对象的最后一个值,具体取决于底层驱动程序。例如,PDO_PGSQL() 要求您为 name 参数指定序列对象的名称。

It should be something like:

它应该是这样的:

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

[EDIT] Update link to doc

[编辑] 更新文档链接

回答by Frank Heikens

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 RETURNINGin the INSERT-statement and fetch the INSERT-result like a SELECT result.

您还可以在 INSERT 语句中使用RETURNING并像 SELECT 结果一样获取 INSERT 结果。

回答by m4tm4t

Previous answers are not very clear (PDO doc too)

以前的答案不是很清楚(PDO 文档也是如此)

In postgreSQL, sequences are created when you are using the SERIALdata 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');