我知道这是一个旧线程,但它是“php Postgres PDO 数组”的第一个谷歌点击,所以我将添加我的答案。马特的答案的问题在于,内爆没有固有的消毒作用。因此,如果 $fieldname 包含引号、逗号、小胡子括号等,它将创建一个无效值。请参阅下面的示例,了解如何使用适当的 PDO 处理数组数据:
// Connect to PostgreSQL database and create test table /////
$dsn = "pgsql:host=$host;dbname=$db;user=$user;password=$pwd";
$psql = new PDO($dsn);
if($psql == null){throw new Exception("Error, db connection returned null.");}
// Set errormode to exceptions
$psql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_table = "
CREATE TABLE IF NOT EXISTS testarray (
id SERIAL PRIMARY KEY,
something TEXT,
test1 TEXT[]
)";
$q_table = $psql->prepare($sql_table);
$q_table->execute();
/////////////////////////////////////////////////////////////
// Create a new row and get it's ID
$sql_new = "INSERT INTO testarray (something) VALUES ('stuff') RETURNING id";
$q_new = $psql->prepare($sql_new);
$q_new->execute();
$r_new = $q_new->fetchAll(PDO::FETCH_ASSOC);
$id = $r_new[0]['id'];
$myarray = array("Test1", "Test2", "test3", "testing4", "TEST5");
// Use a PDO for efficiency and ease of use
// Use the ARRAY_APPEND SQL function to use PDO to add to an array
$sql_up = "UPDATE testarray SET test1 = ARRAY_APPEND(test1, :arr) WHERE id = :id";
$q_up = $psql->prepare($sql_up);
$q_up->bindParam(":id", $id);
// Loop through each element, binding it to the PDO and executing again
foreach($myarray as $elem){
$q_up->bindParam(":arr", $elem);
$q_up->execute();
}
现在在您的数据库中:
testing=# SELECT * FROM testarray;
id | something | test1
----+-----------+------------------------------------
1 | stuff | {Test1,Test2,test3,testing4,TEST5}
(1 row)
testing=#