Preventing errors when using mysql_real_escape_string with no active DB connection

145 views Asked by At

I have inherited a legacy system and it includes this function that is used in many, many places across the site (both front and back end).

function clean_text_for_db($str) {
    $str = trim($str);
    $str = stripslashes($str);
    $str = mysql_real_escape_string($str);
    return $str;
}

It works quite well, generally, however I noticed a bunch of errors in my apache error logs recently when the database was unavailable for a period. The errors were these:

mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established

function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

I understand why the error has occured, however what i'm not sure is how to deal with it to prevent my logs from being hit so much in the event this happens again. Considering the function is used so widely I think a mysql_ping before the mysql_real_escape_string is probably a bad idea as this would mean doing this every time the function is called and 99.9999% of the time this is unnecessary.

1

There are 1 answers

3
Your Common Sense On

That's really simple. Just get rid of this "clean_text_for_db()" function.

And start using PDO prepared statements.