php - 多用户应用程序中的 Postgresql 和 PHP : is the currval a efficent way to retrieve the last row inserted id,?

标签 php postgresql insert-id

我想知道我用来检索插入到 postgresql 表中的最后一行的 id 的方法是否有效..

它显然有效,但是当我有许多用户同时在同一个表中添加行时,引用序列 currval 值可能会出现问题。

我的实际做法是:

$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');

$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");
$last_id_query = pg_query("SELECT currval('customer_id_seq')");
$last_id_results = pg_fetch_assoc($last_id_query);
print_r($last_id_results);
pg_close($pgConnection);

嗯,它只是一个测试 atm。 但无论如何,我可以通过这种方式看到 3 个问题:

  1. 引用 customer_id_seq,如果两个用户在同一时间做同样的事情,可能会发生他们都从那种方式获得相同的 ID ......或者不是?
  2. 必须知道表的序列名称。因为 pg_get_serial_sequence 对我不起作用(我是 postgresql 的新手,可能是配置问题)

有什么建议/更好的方法吗?

p.s:我不能使用 PDO,因为似乎缺少事务保存点;我不会使用 zend,最后,我更喜欢使用 php pg_* 函数(也许我会在最后建立我的类)

编辑:

@SpliFF(删除了他的回答):这样效果会更好吗?

$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');

pg_query("BEGIN");

$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");

$last_id_query = pg_query("SELECT currval('customer_id_seq')");

$last_id_results = pg_fetch_assoc($last_id_query);

print_r($last_id_results);

//do somethings with the new customer id

pg_query("COMMIT");

pg_close($pgConnection);

最佳答案

如果您使用更新版本的 PostgreSQL (> 8.1),您应该使用 INSERT(和 UPDATE)命令的 RETURNING 子句。

OTOH 如果您坚持使用其中一种序列操作函数,请阅读 fine manual .一个指针:“请注意,因为这是返回一个 session 本地值,所以它给出了一个可预测的答案,无论自当前 session 以来其他 session 是否已执行 nextval。”

关于php - 多用户应用程序中的 Postgresql 和 PHP : is the currval a efficent way to retrieve the last row inserted id,?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/892200/

相关文章:

javascript - 在 Laravel 中访问 JavaScript 变量

ruby-on-rails - Rails 无法重置开发数据库

java - 使用 JDBC 连接到 postgres 时是否可以指定架构?

mysql - 什么数据量被认为对 MySQL 来说太大了?

php - mysqli->更新时插入_id (PHP)

PHP – 从扩展插入中检索自动递增的值

PHP、mysql、两条记录主键不变

php - HTML - 包含特殊字符时不发送表单字段

php - 如何将 JavaScript 函数数据放入 PHP 变量中

php - 在单个 FreeBSD 主机上安装多个版本的 Apache、PHP 和 MySQL 的最佳方法