简体   繁体   English

PHP:Postgres数组和pg_insert

[英]PHP: Postgres Array and pg_insert

I know I can insert an array into a Postgres database with pg_query . 我知道我可以使用pg_query将数组插入到Postgres数据库中。

INSERT into table (field) VALUES ('{{element, element},{}}')

But how about using pg_insert ? 但是如何使用pg_insert

$array["field"] = "{{element, element},{}}";
$result = pg_insert($con, "table", $array);

Will the string {{element, element},{}} be actually inserted into field as a 2D Postgres array? 字符串{{element, element},{}}实际上是否会作为2D Postgres数组插入到field中?

I've always wanted to test that out but currently I don't have any PostgreSQL DB to test with.. 我一直想测试一下,但目前我没有任何PostgreSQL数据库来测试..

I just ran your specific example. 我刚刚运行了你的具体例子。

(1) in Postgres: (1)在Postgres:

CREATE TABLE atable (afield text[][]);

(2) in PHP: (2)在PHP中:

$array["afield"] = "{{'element', 'element'},{}}";
$result = pg_insert($this->conn, "atable", $array);

And I got the following error: 我收到以下错误:

Notice: pg_insert(): Unknown or system data type '_text' for 'afield' in ...

I tried playing around with the array value: make it 2x2 array, one-dimensional, etc., etc. - the same result. 我试着玩数组值:使它成为2x2数组,一维等等 - 相同的结果。 I even changed the table to have the field as one-dimensional array: text[] and changed the code accordingly - and I still get the same result. 我甚至改变了表格,将字段作为一维数组: text[]并相应地更改了代码 - 我仍然得到相同的结果。

I started digging further and found the following on PHP documentation for pg_insert : 我开始深入挖掘并在pg_insert PHP文档中找到以下pg_insert

This function is EXPERIMENTAL. 这个功能是实验性的。 The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. 在将来的PHP版本中,此函数,其名称和周围文档的行为可能会更改,恕不另行通知。 This function should be used at your own risk. 使用此功能需要您自担风险。

Basically, it's pretty buggy and shouldn't be used. 基本上,它很漂亮,不应该使用。 Interestingly, using 有趣的是,使用

pg_query("INSERT INTO...")

works just fine. 工作得很好。 Hopefully, this answers your question. 希望这能回答你的问题。 :) :)

As many dimensions as you like, but two is fine. 尽可能多的尺寸,但两个很好。

=> CREATE SCHEMA ztest;
CREATE SCHEMA
=> CREATE TABLE tt (a int[3][3]);
CREATE TABLE
=> INSERT INTO tt VALUES (ARRAY[ARRAY[1,2,3], ARRAY[4,5,6], ARRAY[7,8,9]]), (ARRAY[ARRAY[11,12,13],ARRAY[14,15,16],ARRAY[17,18,19]]);
INSERT 0 2
=> SELECT * FROM tt;
                 a
------------------------------------
 {{1,2,3},{4,5,6},{7,8,9}}
 {{11,12,13},{14,15,16},{17,18,19}}
(2 rows)

=> INSERT INTO tt VALUES ('{{21,22,23},{24,25,26},{27,28,29}}');
INSERT 0 1
=> SELECT * FROM tt;
                 a
------------------------------------
 {{1,2,3},{4,5,6},{7,8,9}}
 {{11,12,13},{14,15,16},{17,18,19}}
 {{21,22,23},{24,25,26},{27,28,29}}
(3 rows)

=> SELECT a[2][3] FROM tt;
 a
----
  6
 16
 26
(3 rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM