Graham recently asked me:
Do I still need to used mysqli_real_escape_string when used prepared statements in PHP?
The simple answer is no.
The way it used to work is that you would take form input data, put that into a variable, and inject that data into your MySQL query in order to add that data to the database.
Now, a big problem with that is SQL Injection attacks where a hacker could inject SQL code into your query and perform actions on your database… which is something you definitely don’t want.
So, the standard solution became using mysql_real_escape_string to sanitize data before sending to the database.
Of course, that’s not the preferred solution anymore. Prepared statements are:
But, with PHP5, the PHP developers built an entire class into PHP for working MySQL. With that class, there are now prepared statements in PHP… and prepared statements allow you to “bind” data to a query using sprintf-like syntax… rather than “inject” your data into those queries.
And, with this new system, the methods that bind the data to your query do the sanitizing for you. So, mysqli_real_escape_string is no longer necessary WHEN you bind values this way.
Of course, if you have some other way you’re injecting input data into your queries, you still need to sanitize that data… and mysqli_real_escape_string is still the main method for doing that.