SQL Injection Tutorial: Learn with Example

โšก Smart Summary

SQL injection is an attack that poisons dynamic SQL statements to bypass authentication or expose data, exploiting web applications that build queries from unsanitized user input. This page shows how the attack works and how to prevent it.

  • ๐Ÿ’‰ Definition: SQL injection inserts malicious SQL into a query through an unvalidated input field.
  • ๐Ÿ”“ Impact: A successful attack can bypass logins and read, modify, or delete records.
  • ๐Ÿงช Example: An always-true condition plus a comment turns a login check into a bypass.
  • ๐Ÿ› ๏ธ Tools: SQLMap and jSQL automate detection and exploitation of injectable parameters.
  • ๐Ÿ›ก๏ธ Prevention: Parameterized queries, input validation, and least-privilege accounts close the gap.
  • ๐Ÿค– Modern edge: AI-driven scanners and firewalls flag injection patterns that fixed signatures miss.

SQL Injection Tutorial

What is a SQL Injection?

SQL Injection is an attack that poisons dynamic SQL statements to comment out certain parts of the statement or append a condition that will always be true. It takes advantage of the design flaws in poorly designed web applications to exploit SQL statements to execute malicious SQL code.

Data is one of the most vital components of information systems. Database-powered web applications are used by organizations to get data from customers. SQL is the acronym for Structured Query Language. It is used to retrieve and manipulate data in the database.

Diagram of how a SQL injection manipulates a dynamic database query

How Does a SQL Injection Attack Work?

The types of attacks that can be performed using SQL injection vary depending on the type of database engine. The attack works on dynamic SQL statements. A dynamic statement is a statement that is generated at run time using parameters passed from a web form or URI query string.

SQL Injection Example

Let us consider a simple web application with a login form. The code for the HTML form is shown below.

<form action=โ€˜index.phpโ€™ method="post">

<input type="email" name="email" required="required"/>

<input type="password" name="password"/>

<input type="checkbox" name="remember_me" value="Remember me"/>

<input type="submit" value="Submit"/>

</form>

HERE,

  • The above form accepts the email address and password, then submits them to a PHP file named index.php.
  • It has an option of storing the login session in a cookie. We have deduced this from the remember_me checkbox. It uses the post method to submit data. This means the values are not displayed in the URL.

Let us suppose the statement at the backend for checking the user ID is as follows.

SELECT * FROM users WHERE email = $_POST['email'] AND password = md5($_POST['password']);

HERE,

  • The above statement uses the values of the $_POST[] array directly without sanitizing them.
  • The password is hashed using the MD5 algorithm.

We will illustrate a SQL injection attack using SQL Fiddle. Open the URL http://sqlfiddle.com/ in your web browser. You will get the following window.

Note: you will have to write the SQL statements.

Empty SQL Fiddle window ready for the schema and query

Step 1) Enter this code in the left pane.

CREATE TABLE `users` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));
  
  
insert into users (email,password) values ('m@m.com',md5('abc'));

Step 2) Click Build Schema.

Step 3) Enter this code in the right pane.

select * from users;

Step 4) Click Run SQL. You will see the following result.

SQL Fiddle result showing the single user record returned

Suppose a user supplies admin@admin.sys and 1234 as the password. The statement executed against the database would be:

SELECT * FROM users WHERE email = 'admin@admin.sys' AND password = md5('1234');

The above code can be exploited by commenting out the password part and appending a condition that will always be true. Let us suppose an attacker provides the following input in the email address field.

xxx@xxx.xxx' OR 1 = 1 LIMIT 1 -- ' ]

xxx for the password.

The generated dynamic statement will be as follows.

SELECT * FROM users WHERE email = 'xxx@xxx.xxx' OR 1 = 1 LIMIT 1 -- ' ] AND password = md5('1234');

HERE,

  • xxx@xxx.xxx ends with a single quote which completes the string quote.
  • OR 1 = 1 LIMIT 1 is a condition that will always be true and limits the returned results to only one record.
  • โ€” โ€˜ AND โ€ฆ is a SQL comment that eliminates the password part.

Copy the above SQL statement and paste it in the SQL Fiddle Run SQL text box as shown below.

SQL Fiddle returning the record after the injected condition runs

Hacking Activity: SQL Inject a Web Application

We have a simple web application at http://www.techpanda.org/ that is vulnerable to SQL Injection attacks for demonstration purposes only. The HTML form code above is taken from the login page. The application provides basic security such as sanitizing the email field. This means our above code cannot be used to bypass the login.

To get around that, we exploit the password field instead. The diagram below shows the steps to follow.

Flow diagram of the steps to inject the login form password field

Let us suppose an attacker provides the following input.

  • Step 1: Enter xxx@xxx.xxx as the email address
  • Step 2: Enter xxxโ€™) OR 1 = 1 โ€” ]

Login form with the injection string entered in the password field

  • Click on the Submit button.
  • You will be directed to the dashboard.

The generated SQL statement will be as follows.

SELECT * FROM users WHERE email = 'xxx@xxx.xxx' AND password = md5('xxx') OR 1 = 1 -- ]');

The diagram below illustrates how the statement is generated.

Breakdown of how the injected SQL statement is generated

HERE,

  • The statement intelligently assumes md5 encryption is used.
  • Completes the single quote and closing bracket.
  • Appends a condition to the statement that will always be true.

In general, a successful attack combines several techniques like those shown above.

Other SQL Injection Attack Types

SQL Injections can do more harm than just bypassing the login algorithms. Some of the attacks include:

  • Deleting data
  • Updating data
  • Inserting data
  • Executing commands on the server that can download and install malicious programs such as Trojans
  • Exporting valuable data such as credit card details, email, and passwords to the attacker’s remote server
  • Getting user login details, etc.
  • SQL injection based on cookies
  • Error Based SQL Injection
  • Blind SQL Injection

The above list is not exhaustive; it just gives you an idea of what SQL Injection can do.

Automation Tools for SQL Injection

In the above example, we used manual attack techniques based on our vast knowledge of SQL. There are automated tools that can help you perform the attacks more efficiently and within the shortest possible time. These tools include:

How to Prevent SQL Injection Attacks

An organization can adopt the following policy to protect itself against SQL Injection attacks.

  • User input should never be trusted – It must always be sanitized before it is used in dynamic SQL statements.
  • Stored procedures – these can encapsulate the SQL statements and treat all input as parameters.
  • Prepared statements – prepared statements work by creating the SQL statement first, then treating all submitted user data as parameters. This has no effect on the syntax of the SQL statement.
  • Regular expressions – these can be used to detect potentially harmful code and remove it before executing the SQL statements.
  • Database connection user access rights – only necessary access rights should be given to accounts used to connect to the database. This can help reduce what the SQL statements can perform on the server.
  • Error messages – these should not reveal sensitive information or where exactly an error occurred. Simple custom error messages such as “Sorry, we are experiencing technical errors. The technical team has been contacted. Please try again later” can be used instead of displaying the SQL statements that caused the error.

Hacking Activity: Use Havij for SQL Injection

In this practical scenario, we use the Havij Advanced SQL Injection program to scan a website for vulnerabilities.

Note: Havij is a dated, unmaintained Windows tool โ€” SQLMap above is the current open-source standard.

Note: your anti-virus program may flag it due to its nature. You should add it to the exclusions list or pause your anti-virus program.

The image below shows the main window for Havij.

Main window of the Havij SQL injection tool

The above tool can be used to assess the vulnerability of a website or application.

FAQs

Only with the site ownerโ€™s written permission. Testing an application you do not own is illegal under laws like the US Computer Fraud and Abuse Act. Bug-bounty scopes define what is allowed.

Yes. In the OWASP Top 10:2025, injection ranks A05, and testing still finds injection in almost every application. With thousands of new SQL injection CVEs a year, it remains a leading web risk.

MD5 is a fast hash, not encryption, and attackers crack it quickly with rainbow tables and GPUs. Use a slow, salted algorithm such as bcrypt or Argon2 for passwords instead.

Any database queried through dynamically built SQL โ€” MySQL, PostgreSQL, Microsoft SQL Server, Oracle, and SQLite. The flaw lies in how the application concatenates user input into queries, not in the database engine.

AI-powered firewalls and scanners learn normal traffic patterns, then flag anomalous inputs such as injected conditions or comments in real time. Machine-learning models catch obfuscated payloads that fixed signatures miss.

AI assistants like GitHub Copilot can suggest parameterized queries and input validation, but they also reproduce insecure patterns. Treat each suggestion as a draft and pair it with a security linter and review.

SQL injection targets the database by injecting SQL into server-side queries. Cross-site scripting targets other users by injecting scripts that run in their browsers. One exposes data; the other hijacks sessions.

An ORM (object-relational mapper) builds queries from code objects with parameterization by default, preventing most SQL injection. It is not foolproof โ€” raw queries and unsafe methods still leak, so validation still matters.

Summarize this post with: