我写了以下代码:
<?php
$listO = $_POST["letter"];
//print_r($listO);
//Array ( [0] => A [1] => B [2] => C)
function to_pg_array($set) {
settype($set, 'array'); // can be called with a scalar or array
$result = array();
foreach ($set as $t) {
if (is_array($t)) {
$result[] = to_pg_array($t);
} else {
$t = str_replace('"', '\\"', $t); // escape double quote
if (! is_numeric($t)) // quote only non-numeric values
$t = '"' . $t . '"';
$result[] = $t;
}
}
return '{' . implode(",", $result) . '}'; // format
}
$pg_array_listO = to_pg_array($listO);
//print_r($pg_array_list_organisms);
//{"A","B","C"}
$conn = pg_connect("host=X dbname=Y user=Z");
$result = pg_query_params($conn, 'SELECT count(cp.id)
FROM cp, act, a, t
WHERE t.tid = a.tid AND
a.aid = act.aid AND
act.m = cp.m AND
t.n = $1 AND
act.st = $2 AND
t.o LIKE ANY(ARRAY[$3])', array($t1, $a2, $pg_array_listO));
while($row = pg_fetch_row($result)) {echo $row[0];}
?>
但是我无法弄清楚如何将数组$pg_array_listO
传递给postgres查询。函数to_pg_array
将php数组转换为postgres数组,但仍无效。我怎么能这样做?
答案 0 :(得分:0)
postgres数组看起来像'{list}'
:
t=# select array['a','b','c'];
array
---------
{a,b,c}
(1 row)
所以你需要摆脱双引号,否则postgres会将文字理解为身份。
例如$pg_array_listO = str_replace('"', '\\"',to_pg_array($listO))
或smth更聪明 - 抱歉 - 我不擅长php
另外修改ANY(ARRAY[$3])
至ANY('$3'::text[])
,费用array[]
或'{}'::text[]
将被接受
<强>更新强> 基于
//print_r($pg_array_list_organisms); //{"A","B","C"}
我希望这可行:
$result = pg_query_params($conn, "SELECT count(cp.id)
FROM cp, act, a, t
WHERE t.tid = a.tid AND
a.aid = act.aid AND
act.m = cp.m AND
t.n = $1 AND
act.st = $2 AND
t.o LIKE ANY($3)", array($t1, $a2, str_replace('"', '',to_pg_array($listO))));
介意我更改了引号和SQL以及$ {3}变量的str_replace
这种方法的一个实例:
t=# select 'a' like any('{a,b,c}'::text[]);
?column?
----------
t
(1 row)