This tutorial will help you to prevent SQL inject in PHP. In this tutorial first, check a basic example of SQL injection process. How can users steal data from your website using SQL injection? This tutorial also includes methods to prevent SQL injection using PHP-MySQLi and PHP-PDO drivers.

Advertisement

Simple SQL Injection Example

For example, A have a website for Bank. You have provided a web interface to bank customers to view their account number and balance. Your Bank website uses URL like http://example.com/get_account_details.php?account_id=102 to fetch details from the database.

For example get_account_details.php have code something like below.

Customers accountId is passed through query string as account_id. Like above Url, if a user’s account id 102 and it passed in the query string. The Php script will create a query like below.

Prevent SQL Injection
Details fetched for specified account.

The accountNumber and balance details are fetched for accountId 102 and provided to customers as showing in above screenshot.

Let’s, assume another scenario – An over smart customer has passed account_id as 0 OR 1=1 in query string. What will be happened now? The PHP script will create a query like below and executed on the database.

Details fetched for all accounts

Look at the query created by script and result returned by the database. You can see that this query returned all accounts number and the available balance.

This is called SQL Injection. This is the simple scenario, there can be a number of methods to do SQL injections. Below tutorial will help you to prevent SQL injection using PHP MySQLi driver and PHP PDO driver.

#1. Using PHP-MySQLi Driver

You can use PHP-MySQLi driver prepared statements to avoid these type of SQL injections. Use below PHP code which will prevent SQL injection.

#2. Using PHP-PDO Driver

You can use PHP-PDO driver prepare statements to avoid these type of SQL injections. Use below PHP code which will resolve above SQL injections.

Share.

3 Comments

  1. I am sure this will come quite handy. It is definitely necessary to review your code and follow PHP coding standards to prevent leaving any SQL injection vulnerabilities in your code. Most commonly, contact forms have SQL injection vulnerabilities in their code, like an example given here: https://www.cloudways.com/blog/protect-php-website-sql-injection/
    In the example mentioned in the code using following code can prevent sql injection attacks

    $userName=BlockSQLInjection($_POST[‘userName’]);
    $password=BlockSQLInjection($_POST[‘password’]);

  2. Actually, the solution here is much more simple:

    $accountId = (int)$_GET[‘account_id’]; // Added strict type conversion

    This will guarantee $accountId as a number no matter what


Exit mobile version