mysql_real_escape_string导致网站连接错误

这个问题已经有了答案:

当我浏览网站时一切正常,该网站与数据库连接并显示结果。然而,每当遇到 mysql resl escape 字符串时,我都会得到这个错误:

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

请注意,网站运行良好,只要我删除 mysql_real_escape_string。但我还是想搞明白哪个细节出了问题?

For mysql_real_escape_string to work, you first have to connect to MySQL via mysql_connect

The error means that the default mysql database connection is not properly configured within your php.ini.

You will likely use mysql_real_escape_string without having connected to the database first, which is the case that PHP will try to connect to the database with the default configuration from php.ini.

In your case these defaults didn't work well, that's all.

Change the configuration and the error goes away - or - provide a valid mysql database connection as parameter to the mysql_real_escape_string function call.

Additional Note: Drop the mysql_* functions to access your mysql database if you're writing new code. Choose Mysqli or PDO instead.

You are using this function wrong way.
Instead of processing only string values right before placing them in the query, you are processing all user input values somewhere at the top of your code.
It will lead you to sql injection

You you passing in the connection variable returned from mysql_connect as the second parameter?

On a side note, you should really be moving over to using PDO, it escapes strings automatically if you use its prepare function.