如何获取元组';s值,该值使用php插入到PostgreSql数据库中


How to get a tuple's values that is inserted into PostgreSql db using php?

我正在尝试使用PHP将元组插入PostgreSql。在插入元组之后,我想要获得插入行的其中一列的值。此列值由数据库自动生成,因为它在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_feach_object&pg_fetch_array。这些似乎都不起作用。(在使用这些功能时,我对代码进行了适当的修改。)

代码中有什么不正确的地方吗?或者我遗漏了什么?

谢谢!

一个好方法是returning子句:

INSERT INTO posts 
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;

我的PHP有点生疏,但它看起来像:

$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
    $row = pg_fetch_row($result); 
    $inserted_id = $row[0];
}