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.

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.

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.

How to Prevent SQL Injection in PHP   TecAdmin - 49How to Prevent SQL Injection in PHP   TecAdmin - 22