Prevent SQL Injection Attacks using PHP & MySQLi

SQL injection is a major threat to Website security now. Most websites on internet are unable to filter SQL injection attacks. SQL injection can be fatal to websites, attacker can delete/change sensitive user information due to developers lack of knowledge or carelessness. This tutorial will explain how to prevent SQL injection with MySQLi Prepared Statements.

Prevent SQL Injection Attacks using PHP & MYSQL

There are a many PHP functions to prevent SQL Injection. Some of them are strip slashes, mysql_real_escape_string etc. But no function can 100% guarantee escape from SQL injection attack. Even the combination of such function can not every time prevent from SQL Injection.

What is MYSQLi?

PHP has built in MYSQL & MYSQLi Extensions for communicating to MYSQL Database. MYSQL extension is old and famous among developers but MySQL extension is deprecated as of PHP 5.5.0 and now PHP has a new MySQLi extension for communicating with MYSQL Database. So we are going to use MySQLi with Prepared Statements for preventing SQL Injection Attacks.

In prepared statements, variables(data) is sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. There is no need of using escape functions on parameters passed because they are never substituted into the query string directly.

Prepared Statements are more secure because a user input is used as part of the SQL statement. You can force the user input to be handled as the content of a parameter (and not as a part of the SQL command itself).

Prepared statement execution consist of two steps:

Step 1:

Prepare Statement Template:

Prepare is followed by execute. During execution the client binds parameter values and send them to the server. The server creates a statement from statement template and bind values to execute it using the previously created internal resources.

Step 2:

Bind data & Execute

Complete Code:


Leave a Reply

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

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

scroll to top