如何使用 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 . "')";

现在终于来回答我的问题:

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

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

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

感谢@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

最新更新