James
James

Reputation: 546

PHP is adding slashes to characters when inserting into MySQL

When a ' is typed into a text field for example, PHP puts a \ before it.

I'm using the following for filtering:

$comment_body = $_POST['comment_body'];
$comment_body = nl2br(htmlspecialchars($comment_body));
$comment_body = mysqli_real_escape_string($db_conx,$comment_body); 

How do I stop this slash from appearing?

Upvotes: 0

Views: 2428

Answers (3)

woofmeow
woofmeow

Reputation: 2408

It may probably be because you have magic quotes on : magic_quotes_gpc If that is the case you can disable it using this

Upvotes: 0

svecon
svecon

Reputation: 551

You should use sanitization with regards to context:

When saving to database use only mysqli_real_escape_string(). When outputing varible to HTML then just go with htmlspecialchars().

Automatic adding of slashes might be due to the settings of magic_quotes_gpc, which is already removed in newer versions of PHP, but you can check your settings in phpinfo();

Upvotes: 1

Orangepill
Orangepill

Reputation: 24665

The is what mysqli_real_escape_string does. This should only be used when putting the data into a database. If you are going to output the $comment_body just leave off the last line of the snippet. If you are getting double escaping happening it is probably the result of the magic quotes configuration directive.

Upvotes: 0

Related Questions