Error when replacing words that contain quotes in mySQL
-
05-07-2019 - |
Question
I have updated many records already, but when it came to a word that contains a quote I get this error: "ERROR: Unclosed quote @ 1357"
I know why it's giving me this error, I just don't how to solve it.
Here's a sample:
UPDATE invnum SET cAccountName
= replace(cAccountName
,'JOHN'S','BEN')
Thanks in advance.
Solution
Escape quotes inside strings:
UPDATE invnum SET cAccountName = replace(cAccountName,'JOHN\'S','BEN')
You want to be really careful with this - not dealing with this properly is the source of SQL injection attacks, and is a major source of security problems.
OTHER TIPS
if you’re using a script to update your records use a builtin escaping function. for php that would be mysql_real_escape_string
Try this instead:
UPDATE invnum SET cAccountName = replace(cAccountName,"JOHN'S","BEN")
If you need to use both types of quotes within a string, then you'll need to escape the type of quotes you use to surround the string when they occur within it (otherwise the SQL interpreter will think the string ends before it actually does.
For instance:
Johns becomes "Johns"
John's becomes "John's" or 'John\'s'
"John" becomes '"John"' or "\"John\""
et cetera.