Zend Framework and mysql_real_escape_string(): Why doesn’t it work?

I had that question asked plenty of times from developers and I just wanted to give a simple clarification and solution.

mysql_real_escape_string() needs a connection to the database using mysql_connecT(). If you are using PDO or mysqli to connect to your database there is no way for mysql_real_escape_string() to find the connection. This is the reason it will not work and prompt you with an error.

There are several ways to fix that.

  • Create a dummy mysql_connect() which will only be used for that. This is not the best solution but it will work.
  • Use $db->QuoteInto(), where $db the object holding your PDO/mysqli connection. This is a ZF function
  • Create your own simple function that will handle XSS injections. (example below)
  • Use $db->quote(), which is the PDO alternative see PDO::quote();

Example of function:

function mres($value) {
$search = array("\x00", "\n", "\r", "\\", "'", "\"", "\x1a");    
$replace = array("\\x00", "\\n", "\\r", "\\\\" ,"\'", "\\\"", "\\\x1a"); 
return str_replace($search, $replace, $value);

I really hope that this helps.

If you have found this article useful, do let me know – leave a comment!