MySQL real escape string

user490895 picture user490895 · Jan 7, 2011 · Viewed 23.6k times · Source

I was trying to sanitize inputs to my PHP login using addslashes and mysql_real_escape_string. Using addslashes works, but mysql_real_escape_string will not.

Here's an example of what allows me to log in correctly:

$user = addslashes($_POST['user']);<br/>
$password = addslashes($_POST['password']);

And this will not:

$user = mysql_real_escape_string($_POST['user']);<br/>
$password = mysql_real_escape_string($_POST['password']);

Also, some of my other fields contain apostrophes. Nothing is returned when using addslashes, since the entry in the DB isn't escaped. I was wondering if using mysql_real_escape_string could fix this, but I don't know how.

Answer

Calum picture Calum · Jan 7, 2011

Always use mysql_real_escape_string instead of addslashes. Make sure you are connected to the database before running it otherwise you will error.