SQL Injection Example

Fews years ago many SQL based websites was attacked by hackers using SQL injection technique. As a web developer you must know how to protect your site against these attacks.

To understand how SQL injection works, I created a simple user database, a login form, and a login php file.


1 jack welcome
2 lara 123456

Login form

<form method="post" action="login.php">
<input type="text" name="user" />
<input type="password" name="pass" />
<button>Log in</button>

Login php


In case login form is submitted this script will process the $_POST variables. Checks if there is a match for the username and password combination in our database. As you can see all posted data go to the MySQL query without any filtering, which makes this script vulnerable for SQL injection.

if( isset($_POST[user]) &&  isset($_POST[pass]) ){

$query = mysql_query("SELECT * FROM users WHERE user = '$_POST[user]' AND password = '$_POST[pass]' ");
$num_rows = mysql_num_rows($query);
    // user found - login successful
    if( $num_rows == 1 ){
    	// do something
    } else {
	// user not found - show error message    

I enter jack as username, and welcome for password into the login form. Let's see how the MySQL query will look like on submit.

SELECT * FROM 'users' WHERE 'username' = 'jack' AND 'password' = 'welcome'

The query returns true, because this username and password combination is found in users table.

Let's use SQL injection to trick the query, allow me to log in without username and password. To do this, just enter the following values to all input fields in login form.

' OR '1' = '1

This is the query:

SELECT * FROM 'users' WHERE 'username' = '' OR '1' = '1' AND 'password' = '' OR '1' = '1'

The query returns true, because 1 = 1 is always true, so I am able to log in without knowing the username and password.

Next to read

In the next article I tell you how to prevent SQL injection.

Go Daddy

Related articles

Email Validation

Email Validation


Learn how to validate email on client side with HTML5, Javascript and on server side with PHP.

Generate Thumbnail on the Fly with PHP

Generate Thumbnail on the Fly with PHP


In a previous artice I already showed you how to generate square thumbnails with PHP. Now I show you how to keep the original ratio of the image and how to control the alignment of the square image.

Facebook Upload Photo to User′s Profile

Facebook Upload Photo to User′s Profile


Learn how to upload a photo to Facebook user′s profile with PHP SDK via Graph API!

Leave a comment

We welcome any comment from you! Please keep in mind that comments are moderated and rel='nofollow' is in use. So, please do not use a domain as your name or a spammy keyword, or your comment will be deleted.

Name: *

E-mail: *

Message: *

Click on the car *

Find us on Facebook


Get online with the world's Best - GoDaddy.com!

Back to Top