Reputation: 341
My original question: insert special characters
I want to insert the """ into database with php, and I use the function to escape the quotes:
$text = str_replace("\"","\\\"",$text);
my original data is:
"support.apple.com/kb/HT4070"
but when I check my database it shows:
\"support.apple.com/kb/HT4070\"
and I want to keep this quote, how can I do it in the php? Thank you very much.
Upvotes: 0
Views: 98
Reputation: 57
For filter in MySQL use mysql_escape_string.
In your way use like this.
$text = mysql_real_escape_string($text);
But this function is deprecated in new versions of PHP. If you using new versions of php read this article. http://php.net/manual/en/function.mysql-escape-string.php
Upvotes: 0
Reputation: 341
The right way I found is:
$text = str_replace("\\","\\\\",$text); // this code changes \ to \\
$text = str_replace("\\\"", "\"",$text); // this code changes \" to "
Upvotes: 0
Reputation: 732
Never do this directly. You can have a SQL Injection attack
If you use PDO, use place hodlders:
$stmt = $pdo->prepare('INSERT INTO texts (text) VALUES (?)');
$stmt->execute([$text]);
Optionally you can also encode the quotes and other bad characters with:
$text4db = htmlentities($text);
By using placeholders you can directly save quoted strings to the database and retrieve it later as you saved them.
In example:
$text = 'My "text" has "quotes"';
$stmt = $pdo->prepare('INSERT INTO texts (text) VALUES (?)');
$stmt->execute([$text]);
// later
$stmt = $pdo->prepare('SELECT text FROM texts LIMIT 1');
$stmt->execute([$text]);
$text = $stmt->fetchColumn();
// now $text has the same text: 'My "text" has "quotes"'
Upvotes: 4