【发布时间】:2015-11-27 17:18:28
【问题描述】:
我正在尝试使用 PHP 将元组插入 PostgreSql。插入元组后,我想获取插入行的列之一的值。该列值由 db 自动生成,因为它在 DDL 中定义为 SERIAL。
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
“posts”表具有以下 DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
当我在表“posts”中插入一行以执行基于 postID 的附加功能时,我想获取“postID”列的值。我已经尝试过 pg_fetch_assoc、pg_fetch_row、pg_fetch_object 和 pg_fetch_array。这些似乎都不起作用。 (在使用这些函数时,我对代码进行了适当的修改。)
代码中是否有错误或我遗漏了什么?
谢谢!
【问题讨论】:
-
可能重复:stackoverflow.com/questions/2944297/… 。基本上,您的插入内容必须是
INSERT INTO ... RETURNING id;
标签: php database postgresql