php - 如何使用 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_id
都phone_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
?
解决方案
感谢@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
!
推荐阅读
- c# - 单元测试项目中的这种结构/场景是否可能?
- javascript - 在 chrome 和 firefox 中获取 api 响应是不同的
- c# - 如何在 Visual Studio 扩展项目中获取预处理的 c++ 代码?
- python - 如何清理 x 轴?
- php - 站点上的 javascript 完成或执行后的简单 HTML DOM 抓取
- git - 如何下载 Chromium 代码的特定文件夹?
- c++ - 滥用函数式宏 max 的流行标头
- node.js - 文件上传无法使用多部分表单数据 api nodejs 在本机反应
- directus - 在基于 Debian 的 VPS 上安装和访问 Directus 时遇到问题
- amazon-route53 - Route 53 管理的 DNS 中的问题