Reputation:
I know I can insert an array into a Postgres database with pg_query
.
INSERT into table (field) VALUES ('{{element, element},{}}')
But how about using 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?
I've always wanted to test that out but currently I don't have any PostgreSQL DB to test with..
Upvotes: 1
Views: 5038
Reputation: 57306
I just ran your specific example.
(1) in Postgres:
CREATE TABLE atable (afield text[][]);
(2) in 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. 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.
I started digging further and found the following on PHP documentation for 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. 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. :)
Upvotes: 3
Reputation: 22893
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)
Upvotes: 0