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.
This Post Has 8 Comments
AWESOME insight.
Thanks! 🙂
Hi! john great job, you have shown how to connect , create data in database, and i really learn a lot, by the way can you post edit and delete database content also?
Thanks! Yeah, I'll look into that.
Do you use any PHP frameworks in your production sites?
Not technically. I work primarily within WordPress, so there’s a code base there, but not an actual framework.
hello Mr. Morris,
I’m little confused about where to use static methods in php and why ?? without Instiating classes.where it’s fits perfactly. advantages and disadvantages . please help me to understand it compleatly . Thanks 🙂
I think this article covers it pretty well: http://phpduck.com/php-static-methods-and-properties/