如何使用php获取自动生成的postgres id的值?

fykwrbwg  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(248)

这个问题在这里已经有答案了

php postgres:get last insert id(2个答案)
10个月前关门了。

问题:

有没有办法得到 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_id 以及 phone_id 创建为 bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 .
因为身份证是 GENERATED ALWAYS AS IDENTITY 在php中将数据插入表时,我不需要指定它们:

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

现在终于来回答我的问题:
每当我插入 client 我还想插入一个 phone ,的 phone 表需要保存对 client 它所属的,它通过拥有 client_id 外键。
如果我只是在php中创建id,我可以在这两种语言中使用该值 INSERT 以正确的行为结束。
有没有办法得到 client.client_id 输入一个php变量,然后将其用作 phone.client_id ?

ibrsph3r

ibrsph3r1#

多亏了@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 !

相关问题