【问题标题】:How can I get the value of an automatically generated postgres id using PHP? [duplicate]如何使用 PHP 获取自动生成的 postgres id 的值? [复制]
【发布时间】:2020-10-31 04:12:02
【问题描述】:

问题:

有没有办法将client.client_id 的值放入PHP 变量中,然后将其用作phone.client_id 的值?

上下文:

我有一个使用 PHP 与之通信的 PostgreSQL 数据库。

我在数据库中有两个单独的表:

client (client_id[PK], client_name) 

phone (phone_id[PK], client_id[FK], phone_number)

client_idphone_id 都创建为 bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807

由于 id 是 GENERATED ALWAYS AS IDENTITY,所以在 PHP 中向表中插入数据时不需要指定它们:

$query = "INSERT INTO public.client (client_name) VALUES('" . $clientName . "')";

现在终于要回答我的问题了:

每当我插入client 时,我还想插入phonephone 表需要保存对它所属的client 的引用,它通过拥有client_id 来实现外键。

如果我只是在 PHP 中创建 id,我可以在两个 INSERT 语句中使用该值并最终得到正确的行为。

有没有办法将client.client_id 的值放入PHP 变量中,然后将其用作phone.client_id 的值?

【问题讨论】:

  • 查看此讨论,您的问题将得到解决:stackoverflow.com/questions/6485778/…
  • 感谢@ErmeSchultz 和@MagnusEriksson,这个问题似乎正是我想要实现的!但是,我不太明白将RETURNING client_id 放在哪里以及之后如何访问该值。我的client_id 会存储在$query 变量中吗?
  • 另一种解决方案可能是在您的 php 脚本中生成 UUID

标签: php sql database postgresql


【解决方案1】:

感谢@ErmeSchultz 和@MagnusEriksson,我能够在this comment 中找到解决方案。

我修改后的代码现在是:

// crafting the query so that the variable $query contains the value of the automatically generated client_id
$query = "INSERT INTO public.client (client_name) VALUES('" . $clientName . "') RETURNING client_id";

// getting an array of the elments contained inside $query
$row = pg_fetch_row($query);

// putting the first element inside $row into $client_id
$client_id = $row[0];

变量$client_id 现在包含client.client_id 的值!

【讨论】:

  • 对此的改进是使用$row = pg_fetch_assoc($query);,以便可以通过$client_id = $row['client_id'];提取值
猜你喜欢
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 2019-08-12
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多