PostgreSQL PDO插入数组类型


PostgreSQL PDO insert into array type

我试图使用PHP PDO将值插入PostgreSQL数据库,但遇到以下错误消息:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: array value must start with "{" or dimension information

字段类型为PostgreSQL数组。

这是我的代码(简化):

try {
  $sql='INSERT INTO table (fieldName, foo) VALUES (?, ?)';
  $fieldName=array('1','2');
  $data=array($fieldName, 'bar'); # fieldName is array type in PostgreSQL
  $STH = $conn->prepare($sql);          
  $STH->execute($data);
catch(PDOException $e) {
  # Handle exception
}

谢谢!

为了防止有人遇到这种情况,解决方案是内爆数组并添加{}。

$fieldName='{'.implode(",",$fieldName).'}';

我知道这是一个旧线程,但它是谷歌对"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=# 

我最近接到了实现类似目标的电话。我会使用json_encode将PHP数组转换为json,并绑定param或值,使其转义所有值,从而消除SQL注入的机会。

$st->bindValue(':arr',json_encode(["jam sandwich","ham sandwich","cheese sandwich"]),'PDO::PARAM_STR);

然后在PDO语句中使用数组聚合函数从json函数构建数组。

例如

SELECT array_agg(ar) FROM 
jsonb_array_elements_text('["jam sandwich","ham sandwich","cheese sandwich"]') ar;

您可以在CTE(Common Table Expression)中使用它来在一个查询中执行插入、更新或其他操作,同时使其安全,因为所有值都是转义的。