Using MySQLi's real_escape_string as a static

2019-02-25 05:58发布

问题:

I'm wondering if I could escape strings (using real_escape_string) without first creating an object instance to apply the function to?

i.e, we can do this:

$database = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$database->real_escape_string($query);
$database->query($query)

etc.

However, what I'm trying to do for consistency within my application, is to have a mostly static database class which is an extension of the MySQLi class, so that I could call: database::real_escape_string($query), a static method.

I do realise that I could build a function which escapes the string manually without MySQL.

回答1:

The short answer is: No.

The long answer is: Well, it's not recommended, for a simple reason - MySQLi's real escape takes into account character encoding, as a certain kind of SQL injection techniques use and abuse of character encoding to bypass common filters. This requires the code to know both the originating (PHP) charset and the receiving (MySQL) charset configurations. This is why it cannot be called statically (and cannot be called until you have a valid link to the server)!

I'd also avoid the procedural version of it, as it simply does the "charset" bit under-the-hood by effectively taking the last server that you connected to, which can lead to fun stuff once you're dealing with multiple database connections simultaneously.



回答2:

mysql_real_escape_string() may help you but you have to establish a connection in both versions. the reason for this is that the application don't know how to escape strings for the database. when connected to database the function asks the database how to escape and what to escape.