0

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.

Community
  • 1
  • 1
ccy
  • 341
  • 6
  • 18

3 Answers3

4

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"'
Community
  • 1
  • 1
Carlos Gant
  • 731
  • 6
  • 15
  • Thank you very much, I don't use PDO, and this is a internal website in my company, I just want to use the simple way to insert the quote. – ccy Mar 04 '16 at 14:58
0

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

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • Hi, thank you, and my php version is 5.5.9, is it fine for using mysql_real_escape_string($text)? – ccy Mar 04 '16 at 17:19
  • Hello after php 5.5.0 mysql_real_escape_string was deprecated. And for this reccomended use mysql- or pdo connectors. – Rashad Aliyev Mar 05 '16 at 20:04
0

The right way I found is:

$text = str_replace("\\","\\\\",$text);   // this code changes \ to \\
$text = str_replace("\\\"", "\"",$text);  // this code changes  \" to "
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
ccy
  • 341
  • 6
  • 18