June 6, 2013

Should I Use mysqli_real_escape_string With Prepared Statements in PHP?

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.

8 Comments on “Should I Use mysqli_real_escape_string With Prepared Statements in PHP?

June 10, 2013 at 12:27 pm

AWESOME insight.

John Morris
June 10, 2013 at 2:42 pm

Thanks! 🙂

July 27, 2013 at 7:52 am

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?

John Morris
July 29, 2013 at 6:29 pm

Thanks! Yeah, I'll look into that.

August 15, 2013 at 4:53 pm

Do you use any PHP frameworks in your production sites?

John Morris
August 15, 2013 at 6:59 pm

Not technically. I work primarily within WordPress, so there’s a code base there, but not an actual framework.

Rahul giri
January 21, 2014 at 3:21 am

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 🙂

John Morris
January 22, 2014 at 10:38 am

I think this article covers it pretty well:


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.