0

I am getting a syntax error in a PostgreSQL query. I am working on a project developed in YII1, I am getting an error

CDbCommand failed to execute the SQL statement: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "s" LINE 1: ...OT NULL AND sub_heading like '%Women and Children's Voices%'.

As you can see above, I am using the like operator in single quotes, and in the string there is another single quote (Children's). So PostgreSQL is throwing me an error. Please provide me a solution to escape the string.

3
  • So where your query? Just show the error not helping.. Commented Nov 13, 2018 at 6:35
  • 1
    '%Women and Children''s Voices%'. Or possibly a backslash instead of doubled quotes; I don't remember which one postgres prefers. Commented Nov 13, 2018 at 6:48
  • Hi @Shawn, thanks for your reply, I did same thing and it works, I replaced single quote with double and it works Commented Nov 13, 2018 at 6:51

3 Answers 3

1

You can escape a single quote in a string by using another single quote (i.e., '' instead of '. Note that these are two ' characters, not a single " character):

sub_heading LIKE '%Women and Children''s Voices%'
-- Here -----------------------------^
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Mureinik, thanks for your answer, Actually value Women and Children was coming from a variable, so I can't change it in the query so I replaced the single quote with double quotes using PHP.
1

You should use the format function to construct the SQL statement, using the %L placeholder for the pattern.

Comments

0

I solved this problem by replacing the single quote with double quotes using PHP. Here is the code There is a variable $var with value Women and Children's Voices. I replace that single quote using the str_replace() function. $var = str_replace("'", "''", $var);

1 Comment

Why are you not using placeholders? Doing this yourself is madness.

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.