1

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?

1 Answer 1

1

Use an array to represent the series of values:

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

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

You can also create a PHP function to receive a PHP array and set it as a valid array for a Postgres prepared statement as in:

function php_array_to_pg ($array) {

    $values = "";

    foreach ($array as $value) {
        if ($values=="") {
        $values = $value;
        } else {
        $values = $values.",".$value;
        }
    }

    return "{".$values."}";
}

Then you make a statement such as:

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

$array = array(1,2,3,4);

pg_execute($con, "prep", array(php_array_to_pg ($array)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.