首页 > 解决方案 > 如何使用 PHP 获取自动生成的 postgres id 的值?

问题描述

问题:

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

语境:

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

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

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 . "')";

现在终于解决我的问题了:

每当我插入 aclient我也想插入 aphone时,phone表需要保存client对其所属的引用,并且它通过具有client_id外键来实现。

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

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

标签: phpsqldatabasepostgresql

解决方案


感谢@ErmeSchultz 和@MagnusEriksson,我能够在此评论中找到解决方案。

我修改后的代码现在是:

// 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!


推荐阅读