php - 在postgres中的多行中插入数组

标签 php arrays postgresql

我有一个存储数组的变量, 例如 print_r ($template); 给出以下输出

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

我想将这些值插入到具有 2 列(id、模板)的 postgres 表中。

$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

关于php - 在postgres中的多行中插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44565841/

相关文章:

javascript - Ajax Promise 是同时执行的,而不是顺序执行的

php - 方法链的影响

php - session VS 温度。 cookies

java - 数组索引越界异常(Java)

c - 如何在 C 中将指针转换为 double?

php - 如何通过 jQuery.ajax() 将多个参数传递给 PHP?

javascript 数组返回 [object Window] 而不是数组内容

postgresql - 为什么在 SELECT COUNT(DISTINCT) 中没有使用索引?

sql - 如何创建一个已经安装了 hstore 扩展的新数据库?

sql - 条件左连接最大日期和第二个表中的 where 子句