HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

PostgreSQL PREPARE query with IN () parameters

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlwithqueryparametersprepare

Problem

I'm trying to prepare a query from PHP like:

pg_prepare($con, "prep", "select * from test where tid in ($1)");


and then execute it with:

$strpar = "3,4,6,8,10";
pg_execute($con, "prep", array($strpars));


The problem is that I cannot pass a series of values built as prepare expects a fixed number of parameters. Is there any way to make the parameters dynamic?

Solution

Use an array to represent the series of values:

pg_prepare($con, "prep", "select * from test where tid=ANY($1::int[])");

$strpar = "{3,4,6,8,10}";
pg_execute($con, "prep", array($strpars));


The cast to int[] in the query might even be superfluous if the planner is able to infer the type by itself.

Code Snippets

pg_prepare($con, "prep", "select * from test where tid=ANY($1::int[])");

$strpar = "{3,4,6,8,10}";
pg_execute($con, "prep", array($strpars));

Context

StackExchange Database Administrators Q#55009, answer score: 16

Revisions (0)

No revisions yet.