3

I am getting the error:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Why do I get this error? The mysql_real_escape_string() works on all of my pages apart from one? Is it something to do with MySQL being on a different server to the PHP server - if so, how do I fix it?

$fname = $_POST['fname'];
$fname = stripslashes($fname);
$fname = mysql_real_escape_string($fname);
Tom
  • 159
  • 2
  • 3
  • 6

1 Answers1

9

This is because you never call mysql_connect() before the use of mysql_real_escape_string().

In order to use mysql_real_escape_string(), PHP must be connected to the database. In order to connect to the database, you must use mysql_connect().

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • Out of curiosity, why does it need to call the database to execute that function? – Spencer Ruport Mar 21 '10 at 21:42
  • The PHP code invokes the MySQL's library function to escape the strings, so in order for the code to invoke the library function, it must be connected first. – Anthony Forloney Mar 21 '10 at 21:45
  • It calls a MySQL library function to do the escaping. It is not done in PHP directly. – Sasha Mar 21 '10 at 21:45
  • @Spencer Good question. It's because the escaping depends on the character set used by the server ( see http://dev.mysql.com/doc/refman/5.1/en/mysql-real-escape-string.html ) – John Carter Mar 21 '10 at 21:47