Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Basic SQL Injection and Mitigation with Example
Next article icon

Basic SQL Injection and Mitigation with Example

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker).

  • SQL Injection can be used in a range of ways to cause serious problems.
  • By levering SQL Injection, an attacker could bypass authentication, access, modify and delete data within a database.

For a moment, place yourself in the role of an attacker. Your goal is simple. You want to get any unexpected SQL statement executed by the database. You're only looking to get something to work because that will reveal the fact that the application has a potential vulnerability. For example, consider the simple authentication form shown in Figure 1.

      Capture
Figure 1

Code for Figure 1

HTML
<form action="/login.php" method="POST"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="text" name="password" /></p> <p><input type="submit" value="Log In" /></p> </form> 

You can already make a very educated guess about the type of SQL statement that this application might use to verify the access credentials. It will most likely be a SELECT statement. You can also make a guess about the naming convention used in the database table because it probably matches the simple names used in the HTML form. Because this form is for authentication, there is probably WHERE clause that uses

$_POST['username'] and $_POST['password'].

From all of this, you might predict the following:

PHP
<?php $sql = "SELECT count(*) FROM users WHERE                username = '{$_POST['username']}'AND                password = '...'"; ?> 

Assuming this guess is correct, what can you do to manipulate this query? Imagine sending the following username:

akash' /*
SQL
SELECT count(*)FROM users WHERE username = 'akash' /*'AND password = '...'"; 
In this example, /* is used to begin a multi-line comment,
effectively terminating the query at that point. This has
been tested successfully with MySQL. A standard comment
in SQL begins with --, and it's trivial to try both.

This query suggests a successful authentication attempt as long as the akash account exists, regardless of the password. This particular attack is frequently used to steal accounts. Of course, any username can be used (admin is a popular target). Thus, by sending a malformed username, you can manage to log in without having a valid account.

Mitigation using Prepared Statements (Parameterized Queries)

There are a lot of ways to defend SQL injection. One of the primary defense techniques is "Prepared Statements (Parameterized Queries)". This technique force the developer to define all the SQL code and then pass in each parameter to the query later. This style allows the database to differentiate between code and data, regardless of what user input is supplied. Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. For example, if an attacker enters the userID of ABC or '1'='1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string ABC or '1'='1. Working:

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example:
    SELECT count(*)FROM users WHERE username = ? AND password = ?;
  2. Parse: The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.
  3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.

Implementation:

PHP
<?php  $stmt = $dbConnection->prepare('SELECT count(*)FROM users WHERE username = ? AND password = ?');  $stmt->bind_param('ss', $username,$password);  $stmt->execute();  $result = $stmt->get_result();  echo $result; ?> 

This is just a simple example of bypassing user login page whereas SQL Injection can provide an attacker with unauthorized access to sensitive data including, customer data, personally identifiable information (PII), trade secrets, intellectual property, and other sensitive information. There is also an SQL Injection Automation tool sqlmap that is used to perform all type of SQL injection.

So we have to apply Secure Coding so that system will be protected from being compromised.

Related Article :

Mitigation of SQL Injection Attack using Prepared Statements (Parameterized Queries)

Next Article
Basic SQL Injection and Mitigation with Example

A

Akash Sharan
Improve
Article Tags :
  • Misc
  • GBlog
  • Technical Scripter
  • TechTips
Practice Tags :
  • Misc

Similar Reads

    Command Injection Vulnerability and Mitigation
    Command injection is basically injection of operating system commands to be executed through a web-app. The purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. In situation like this, the application, which executes unwan
    3 min read
    Spring Dependency Injection with Example
    Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of
    7 min read
    Commix - OS Command Injection and Exploitation Tool
    In terms of security, we also refer to command injection as shell injection and operating system injection. Command injection lies in the OWASP top 10 every year. Command injection is a hacking technique in which hackers execute commands in the host operating system through vulnerable web applicatio
    3 min read
    Difference Between XSS and SQL Injection
    Cyber security has become an essential part of the digital world due to the rise in malicious attackers. Cyber security ensures to the protection of data, and systems from cyber attacks like Denial of Service attacks, Ransomware attacks, Virus attacks, etc. These attacks are possible by finding vuln
    4 min read
    Authentication Bypass using SQL Injection on Login Page
    SQL injection is a technique used to exploit user data through web page inputs by injecting SQL commands as statements. Basically, these statements can be used to manipulate the application’s web server by malicious users. SQL injection is a code injection technique that might destroy your database.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences