Search code examples
phpsql-injectionmysql-real-escape-string

When does mysql_real_escape_string know which db server is in charge at the moment?


In a function call like this

$rs = getrs($dbh,"select firstname,lastname from users where userid='" . safe($uid) . "'")

would the safe function properly handle the sql injection?

the safe function basically does nothing but applying the mysql_real_escape_string over the passed argument which in this case is $uid.

If so, I don't see how.

I don't see how that would work cause the database handle $dbh and the function safe() are running in different contexts.

Is there a way to write a convenient function like the above one liner while making sure all the variables that are wrapped in a safe like function are properly escaped.

and also is there a function in PHP, that you pass the 4dbh and it tells you whether it's a mysql or mssql handle?


Solution

  • When does mysql_real_escape_string know which db server is in charge at the moment?

    From the manual:

    If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

    [...]

    would the safe function properly handle the sql injection?

    In your particular case, yes it would.

    Is there a way to write a convenient function like the above one liner while making sure all the variables that are wrapped in a safe like function are properly escaped.

    Some people like to use sprintf for this. However, the correct way to do this now is using parameterized queries (PDO).

    and also is there a function in PHP, that you pass the 4dbh and it tells you whether it's a mysql or mssql handle?

    You could use get_resource_type

    $dbh = mysql_connect();
    echo get_resource_type($dbh); // mysql link