gpt4 book ai didi

php - 如何在任何条件下将 php 数组传递给 postgres 查询

转载 作者:行者123 更新时间:2023-11-29 12:25:09 25 4
gpt4 key购买 nike

我写了下面的代码:

<?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 数组,但仍然不起作用。我该怎么做?

最佳答案

postgres 数组看起来像 '{list}' :

t=# select array['a','b','c'];
array
---------
{a,b,c}
(1 row)

所以你需要去掉双引号,否则 postgres 会将文字理解为身份。

例如 $pg_array_listO = str_replace('"', '\\"',to_pg_array($listO)) 或更聪明 - 抱歉 - 我不擅长 php

另外修改ANY(ARRAY[$3])ANY('$3'::text[]),cos 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))));

请注意,我为 $3 变量更改了引号和 SQL 以及 str_replace

这种方法的一个工作示例:

t=# select 'a' like any('{a,b,c}'::text[]);
?column?
----------
t
(1 row)

关于php - 如何在任何条件下将 php 数组传递给 postgres 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com