PostgreSQL PDO插入数组类型

问题描述 投票:4回答:3

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

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

字段类型是PostgreSQL Array

这是我的代码(简化):

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
}

谢谢!

php sql arrays postgresql pdo
3个回答
2
投票

万一有人遇到过这种情况,解决办法是内爆数组并添加{}。

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

1
投票

我知道这是一个老线程,但它是第一个谷歌打“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=# 

0
投票

我最近打电话来实现类似的东西。我会使用json_encode将PHP数组转换为json并绑定param或值,以便它转义所有值 - 从而消除SQL注入的机会。

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

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

EG

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

您可以在CTE(公用表表达式)中使用它来在单个查询中执行插入,更新或其他任何操作,同时在所有值都被转义时使其安全。

© www.soinside.com 2019 - 2024. All rights reserved.