簡體   English   中英

在postgres中的多行中插入數組

[英]Insert array in multiple rows in postgres

我有一個存儲數組的變量,例如print_r ($template); 給出以下輸出

Array
(
   [0] => 351
   [1] => 352
)

我想在postgres表中插入這些值,該表有2列(id,template)。

$sql = 'INSERT INTO "table"("id", "template") values ('."'$id'".','."'unnest($template)'".')';
$result = pg_query($sql);

得到以下錯誤

invalid input syntax for integer: "unnest(Array)"

想要輸出就好

----------
id | template
----------
12 | 351
----------
12 | 352
----------

我假設id 不是主鍵

需要做的如下: -

foreach($template as $temp){
 $sql = "INSERT INTO `table`(`id`, `template`) values ($id,$temp)";
 $result = pg_query($sql);
}

或者如下所示: -

$values = "";
foreach($template as $temp){
  $values .= "('".$id.",'".$temp."')";
}
$sql = "INSERT INTO `table`(`id`, `template`) values $values";
$result = pg_query($sql);

輸出: - https://eval.in/817145

使用Pomm保持簡單:

<?php //…
$sql = <<<SQL
INSERT INTO table (id, template)
  SELECT $*::int4 as id, unnest($*::int4[]) as template
RETURNING id, template
SQL;

$results = $pomm['my_session']
    ->getQueryManager()
    ->query($sql, [12, [351, 352]]);

foreach ($results as $result) {
    printf(
        "id:%d => template:%d\n",
        $result['id'],
        $result['template']
        );
}

pg_insert更適合執行此查詢,關聯數組的鍵是表的列名,值是您要插入的數據。 您可以查看https://www.php.net/manual/ru/function.pg-insert.php

$data = Array
(
   [id] => 351
   [template] => 352
)

 $res = pg_insert($dbconn, 'post_log', $data);

  if ($res) {
      echo "data has been inserted\n";
  } else {
      echo "an error occurred\n";
  }```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM