Using mysql_real_escape_string with PDO (no connection to localhost server)

Julian H. Lam picture Julian H. Lam · May 31, 2011 · Viewed 11.5k times · Source

So I'm fairly paranoid and use mysql_real_escape_string() with PDO. I actually don't use prepared statements in PDO, so I do have to sanitize the inputs.

When hosting on my own server, I'd create an unprivileged user on the local machine so mysql_real_escape_string() wouldn't fail and empty my variable (heh, now that's sanitization!). I realize this is a pretty fail solution, since if the db's don't have matching charsets, then there's no point to the sanitizing at all, but it worked for the interim.

Now at my new host, I can't create an unpassworded, unprivileged user for the database... and mysql_real_escape_string() fails because there is no mysql server on the local machine. I can't edit php.ini to set the hostname/user/pass for the default database.

What can I do?

Brainstorming as I am writing this, I am wondering if php allows runtime changes to the config... maybe... hrm. Edit: Hm... ini_set()? :O

Answer

Pekka picture Pekka · May 31, 2011

Mixing two database libraries like this is a bad idea and potentially unsafe.

mysql_real_escape_string() needs an existing, classic mysql_connect() database connection (which it can get character set info from) to be totally safe. The PDO connection will be separate, possibly with different character set settings, ultimately resulting in less security:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Use PDO all the way, there's no alternative.

If you don't want to use prepared statements, PDO::quote should be the correct function:

Returns a quoted string that is theoretically safe to pass into an SQL statement.

Note however that even the manual page for that function recommends using prepared statements instead.