带有数组字段PostgreSQL& PHP的Prepared语句

时间:2014-08-26 12:17:20

标签: php arrays postgresql multidimensional-array parameter-passing

有下表:

CREATE TABLE submission (
    num SERIAL,
    user_id INTEGER NOT NULL,
    assignment_id INTEGER NOT NULL,
    timestamp TIMESTAMP,
    lti_info TEXT[][],
    PRIMARY KEY(num),
    FOREIGN KEY (user_id) REFERENCES canvas_user,
    FOREIGN KEY (assignment_id) REFERENCES assignment
);

我想用php函数在表上创建INSERT,类似于以下(不工作)代码:

function create_submission($user_id, $assignment_id, $lti_info) {
        # INSERT everything except lti info
        $query = "INSERT INTO submission (user_id, assignment_id, timestamp) VALUES ($1, $2, LOCALTIMESTAMP) RETURNING num";
        pg_prepare($this->con, "createsub", $query);
        $rs = pg_execute($this->con, "createsub", array($user_id, $assignment_id));
        $row = pg_fetch_row($rs);
        $sub_num = $row[0];

        # update table to insert lti_info
        $serialized = serialize($lti_info);
        $query = "UPDATE submission SET lti_info = $1";
        pg_prepare($this->con, "insertlti", $query);
        pg_execute($this->con, "insertlti", array($serialized));
        return $sub_num;
    }

我试图在类似的问题上序列化并做类似这样的答案:Supply a prepared statement with an array,但没有成功。

如果你们中的任何人能够为create_submission函数提供解决方案,我将非常高兴。

更新

当我执行create_submission时,它在更新点发出以下错误:

  

pg_execute():查询失败:错误:数组值必须以“{”或“。”开头   维度信息

lti_info是字符串的关联数组,类似于:

lti_info = array (
"oauth_consumer_key" => "example",
"oauth_consumer_secret" => "secret"
)

注意:我不介意是在一个插入中完成所有操作,还是先插入“普通”字段然后插入lti_info数组。

1 个答案:

答案 0 :(得分:1)

Postgresql中没有关联数组。要将其保存为二维数组,有必要构建一个合适的字符串以传递给Postgresql,并在返回的过程中执行相反的操作。将它保存为JSON更简单:

create table submission (
    num serial,
    user_id integer not null,
    assignment_id integer not null,
    timestamp timestamp,
    lti_info json,
    primary key(num)
);

使用json_encode

<?php
$lti_info  = array (
    "oauth_consumer_key" => "example",
    "oauth_consumer_secret" => "secret"
);

$query = "
    insert into submission (user_id, assignment_id, timestamp, lti_info) values
    ($1, $2, localtimestamp, $3)
    returning num
";

$conn = pg_connect ( "port=5432 user=cpn dbname=cpn");
pg_prepare($conn, "createsub", $query);
pg_execute($conn, "createsub", array(1, 1, json_encode($lti_info)));

$query = "select * from submission";
pg_prepare($conn, "select", $query);
$rs = pg_execute($conn, "select", array());

$lti_info = (array) json_decode(pg_fetch_result($rs, "lti_info"));

print_r ($lti_info);
?>

输出

    Array
(
    [oauth_consumer_key] => example
    [oauth_consumer_secret] => secret
)