【问题标题】:How to get a tuple's values that is inserted into PostgreSql db using php?如何获取使用 php 插入 PostgreSql db 的元组值?
【发布时间】: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。这些似乎都不起作用。 (在使用这些函数时,我对代码进行了适当的修改。)

代码中是否有错误或我遗漏了什么?

谢谢!

【问题讨论】:

标签: php database postgresql


【解决方案1】:

一个好方法是returning clause:

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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多