I have a php variable referring to a string that contains apostrophes, but when I quote this variable, it thinks I am trying to end the string. My variable is reading from an array of table data, so I can not go in and put a "\" before every apostrophe in the table. If $foo
contains the string "don't", how do I correctly say '$foo'
without it trying to end the string. Thanks.
Asked
Active
Viewed 1,623 times
-2

maustin
- 21
- 6
-
You need to learn about _escaping_. – SLaks May 21 '17 at 18:43
-
1this seems db-related and that quote is being taken as an sql injection. The question's unclear though due to lack of code. In any case, use a prepared statement. – Funk Forty Niner May 21 '17 at 18:46
-
If you're not going to update your question to hold the full code for this, then I for one cannot help you. The question could also get closed with a few possible duplicates. For that (being unclear) I gave the question a -1. – Funk Forty Niner May 21 '17 at 18:50
2 Answers
1
You are correct in thinking that you need to add escape characters ("\") before the apostrophes.
To do this on the fly with the database data you can use the php function addslashes.
so:
$escapedString = addslashes($string);
You could also do this with the string replace function for higher precision:
$escapedString = str_replace("'", "\'", $string);

Tom_B
- 307
- 2
- 8
0
You can use PHP's addslashes PHP Manual - Add slashes
$foo = addslashes($foo);

Funk Forty Niner
- 74,450
- 15
- 68
- 141

ChrisD
- 147
- 5