How can I Prevent SQL Injection in PHP?

How can I prevent SQL injection in PHP?

In this article, we will use the best way to do modification into SQL query to prevent SQL injection using PHP.

We will use parameterized queries and prepared statements to protect a database from SQL injection by hackers.

What is SQL injection?

SQL injection in PHP is a common and popular technique or method used by hackers to access the database of your website and can destroy it OR they can also use our information in the wrong way.

When malicious code embedded into SQL query by user input inserted then our website or application becomes vulnerable and the hacker can access our whole database.

So let’s start to become a father of hackers 😉

Use SQL Parameters and Prepared Statements for Protection

To protect a website OR application from SQL injection by attackers, you can use SQL Parameters and Prepared statements.

SQL Parameters are values that are added in SQL query and Prepared statements are an execution method of SQL query.

You have two options to do this.

Using MySqli:

See this code below, how you can use a prepared statement and parameters.

Using PDO:

See this code below, how you can use a prepared statement and parameters.

NOTE: I want to let you know that, when we are using PDO to connect with MySQL database then prepared statement are not allowed by default. You have to enable this by disabling emulation of prepared statements.

Look at the example connection creating with PDO:

Using mysql_real_escape_string():

We can also use mysql_real_escape_string() function to escape characters from string to prevent SQL injection. But if you are using a recent version of PHP (7.*.*) then this function will no longer be available in an entirely new version of PHP.

So for this you can use escape_string(). We can also still use mysql_real_escape_string() function but its only for legacy of PHP.

mysql_real_escape_string() function take a string by prevent SQL injection in PHP and return us to same string and escaped extra quotes(”) from string and return safe SQL query.

Look at the example:

You May Also Like

About the Author: Aman Mehra

Hey! I'm Aman Mehra and I'm a full-stack developer and have 5+ years of experience. I love coding and help to people with this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *