mysql_real_escape_string() not working, even though I'm connected to the database

user460847 picture user460847 · Mar 31, 2012 · Viewed 15.4k times · Source

I don't think my code's the problem because it's working on my local server (EDIT: sorry if this was the wrong place to ask, but I can't move to ServerFault by myself). On the remote server, though, I can't get mysql_real_escape_string() to work. The database connection is working, and I'm connecting before calling the function.

When I try echo $_POST['email'];, I get the right data, but when I try echo mysql_real_escape_string($_POST['email']); I get nothing.

Here's I get when I leave error reporting on:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: [2002] No such file or directory (trying to connect via unix://please_see_the_faq) in /f5/mysite/public/email_results.php on line 11

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: No such file or directory in /f5/mysite/public/email_results.php on line 11

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /f5/mysite/public/email_results.php on line 11

Is it possible that something with the PHP configuration is causing this? I'm hosting with NearlyFreeSpeech, if it matters.

Here's my insert code:

$db->query('INSERT INTO emails VALUES ("[email protected]")');

And here's how I'm connecting to the database:

@ $db = new mysqli('mysite.db', 'wizard', '(password)', 'mysite');

Answer

cHao picture cHao · Mar 31, 2012

You see that first error...the one saying "trying to connect via unix://please_see_the_faq"? That means PHP is trying to connect to your MySQL server (the same as it would via mysql_connect with no params), but it doesn't have the correct params to connect. It doesn't even know where the database socket is.

If you're not connecting to the database using mysql_connect, then you shouldn't be using mysql_real_escape_string. If you do, then it'll try to connect to the database on its own, using the default params in php.ini (the results of which, you're currently seeing). It looks like you're using mysqli, which is a whole different extension, and has its own escape function -- mysqli_real_escape_string. Use that instead.

Or, get a clue and learn to use prepared statements as the gods intended.