1

I have a query that uses an array as follows:

SELECT * FROM devices WHERE code = ANY ('{"value1","value2","..."}');

If value1 is instead val"ue1 the query will fail. I can solve this by using a backslash before the double quote. I'm trying to escape this using standard pg_ functions however pg_escape_string, pg_escape_literal or pg_escape_identifier don't appear to format the strings correctly.

  • Is there a specific function to escape these types of array or do I just use write my own?

  • Are there any better suggestions as to how I could write the query?

Ideally I'd like to use parameterized queries for this but it doesn't seem possible to pass arrays as parameters in pg_query_params()

Many thanks in advance.

2
  • The manual says otherwise. params - An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders. Commented Feb 3, 2021 at 20:39
  • But you can't assign $a=array() then do pg_query_params($conn,"SELECT * FROM table WHERE id=ANY($1)",[$a]); php and/or postgres throws an error. Commented Feb 4, 2021 at 9:14

1 Answer 1

1

You can use this modified version of the query:

SELECT * FROM devices WHERE code = ANY (ARRAY['value1','value2','...']::text[]);

Escape value1 .. valueN using pg_escape_string and enclose them in single quotes.

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

1 Comment

Thanks. Appreciate the help.

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.