Using mysql_real_escape_string with PDO (no connection to localhost server)

11,573

Solution 1

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.

Solution 2

The usefulness of using PDO is to don't worry about escape stuff.

I suggest you to use prepare and let PDO do the dirty job.

Share:
11,573
Julian H. Lam
Author by

Julian H. Lam

Founder of NodeBB Inc., curator of the NodeBB open-source project. Experienced in Javascript, (X)HTML, CSS, php, (my)SQL, server administration, Linux, etc... GitHub Profile

Updated on June 28, 2022

Comments

  • Julian H. Lam
    Julian H. Lam almost 2 years

    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