PHP Postgresql using IN with pg_query_params


PHP Postgresql using IN with pg_query_params

我可以传递值到这个查询吗?如果是,$arr的格式是什么?

$sql = "SELECT * FROM tree WHERE tree_id IN ($1);";
$result = pg_query_params($sql, [$arr]);
$sql = "SELECT * FROM tree WHERE tree_id = ANY ($1)";
$result2  = pg_query_params($sql2,[$arr]);

$arr format example = "{12,13}"

如果您的SQL语句包含一个IN子句,该子句接受不同数量的参数,那么使用参数化查询有点棘手。正如你所发现的,你可以通过使用ANY而不是IN来解决这个问题,然后传递一个PostgreSQL数组作为唯一的查询参数。

$sql = 'SELECT * FROM tab WHERE id = ANY ($1);';
$id_array = [ 1, 2, 3 ];        // id_array can be of any size
$result = pg_query_params($sql, [ toPostgresArray($id_array) ]);

其中toPostgresArray()是下面的辅助函数,它将PHP数组转换为PostgreSQL数组:

function toPostgresArray($values) {
    $strArray = [];
    foreach ($values as $value) {
        if (is_int($value) || is_float($value)) {
            // For integers and floats, we can simply use strval().
            $str = strval($value);
        } else if (is_string($value)) {
            // For strings, we must first do some text escaping.
            $value = str_replace('''', '''''', $value);
            $value = str_replace('"', '''"', $value);
            $str = '"' . $value . '"';
        } else if (is_bool($value)) {
            // Convert the boolean value into a PostgreSQL constant.
            $str = $value ? 'TRUE' : 'FALSE';
        } else if (is_null($value)) {
            // Convert the null value into a PostgreSQL constant.
            $str = 'NULL';
        } else {
            throw new Exception('Unsupported data type encountered.');
        }
        $strArray[] = $str;
    }
    return '{' . implode(',', $strArray) . '}';
}