0

I am trying to protect against sql injections by using mysql_real_escape_string before inserting data to the database:

$data=mysql_real_escape_string($_POST['data']);

Now, the data is stored as such:

That\\\'s an apostrophe.\r\n\r\nThis new line isn\\\'t displaying properly!

So, I am trying to get it to display correctly inside of a textarea after pulling it back out of mysql:

$data = nl2br($data);

For whatever reason, this does NOTHING. I've even tried str_replace to replace the \r\n's with a <br>, but then the <br> just displays within the textarea.

How do I get what's in my mysql to display as:

That's an apostrophe.

This new line isn't displaying properly!
MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • Verify your code. It appears you are escaping that string multiple times. The output from `mysql_real_escape_strin` should be: `That\'s an apostrophe. This new line isn\'t displaying properly!`. Which would come out properly. – phpisuber01 Nov 30 '12 at 13:04
  • be aware that the `mysql_xxx()` functions are considered obsolete and insecure (even if you are escaping properly). They are also being deprecated, which means that they may be removed from PHP in a future version. It is recommended to switch to the equivalent `mysqli_xx()` functions, or the PDO library. See also http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-function-in-php – SDC Nov 30 '12 at 14:06

3 Answers3

2

The Best Solution..

$data= mysql_real_escape_string($_POST['data']); (You can insert it in your database if you want)

echo stripslashes(str_replace('\r\n',PHP_EOL,$data)); (The output is exactly as your input was)

Giorgos Tsakonas
  • 5,845
  • 3
  • 17
  • 20
1

Actually using mysql_real_escape_string doesn't fully protect you from SQL Injection attack.

The best way to do is to use PDO or MySQLi.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

you probably have magic_quotes turned on, check it with
echo get_magic_quotes_gpc() or else you will double quote

"Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically. "

by the way, it's not a good ideia to use magic_quotes, try using one of this classes.

PDO http://br2.php.net/manual/en/book.pdo.php or mysqli http://br2.php.net/manual/en/book.mysqli.php

Rafael Rotelok
  • 1,102
  • 1
  • 14
  • 26