Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MySQLi's real_escape_string as a static function

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.

like image 621
bear Avatar asked Jan 15 '23 00:01

bear


1 Answers

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.

like image 127
Sébastien Renauld Avatar answered Jan 19 '23 00:01

Sébastien Renauld