1

I'm trying to use a query where the schema and table are passed as parameters into a prepared statement using pg_query_params like this:

$searchSchema = 'mySchema';
$searchTable = 'myTable';
$searchColumn = 'searchColumn';
$searchValue = 'some value';

$selQuery = "SELECT *

FROM $1.$2  --fails here

WHERE someColumn like $3;";

$rs = pg_query_params($db, $selQuery , array($searchSchema, $searchTable, $searchColumn, $searchValue));

The issue is with the schema and table which need to be set dynamically - as in the code above.

8
  • @Laurenz Albe please could you remove the 'marked as duplicate' please? Commented Nov 6, 2017 at 15:39
  • Sure, if you can explain what is different... Commented Nov 6, 2017 at 15:59
  • 1
    In essence, you have to compose the query as a string. You cannot use parameters for table or column names. Commented Nov 6, 2017 at 16:02
  • 2
    In essence it is the same thing. You can neither use table names nor column names as parameters to a prepared statement, neither with pg_query_params or otherwise. PostgreSQL does not allow it, there is nothing PHP can do about it. Commented Nov 7, 2017 at 19:40
  • 1
    Ok, ok. I thought you would be satisfied with being pointed towards the solution, but I'm happy to write up an answer if that is better for you. Commented Nov 8, 2017 at 8:31

1 Answer 1

3

In a parameterized SQL statement (which is a prepared statement in PostgreSQL), parameters can only stand for constant values, not for table or column names.

This limitation is enforced by PostgreSQL, and there is no way around it, no matter what programming language or driver you use. This is also intentional and not a bug.

You will have to compose a string that contains the complete SQL statement with table and column names substituted and execute that. Beware of SQL injection – use functions like pg_escape_identifier to escape names.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.