我有一个存储数组的变量,
例如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
----------
答案 0 :(得分:2)
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";
}```
答案 1 :(得分:0)
我假设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
答案 2 :(得分:0)
使用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']
);
}