Learn About SQL Injections and How to Prevent Them

SQL Injections

An SQL Injections is a vulnerability that occurs when you give an attacker the ability to influence the Structured Query Language (SQL) queries that are passed to a back-end database form through a Web application. The point of an SQL Injection attack is to compromise the database, which is an organized collection of data and supporting data structures. The data can include user names, passwords, text, etc.

These fragmented requests are then combined by the web application into valid SQL requests that is sent to the database and run by it. The database then performs the action mentioned in these SQL results causing a data breach on it. The requests could range from anything to running a virus on to the PC or accessing sensitive data and sending it to a third-party. For example, an SQL injection to a bank’s server can result it to gain access to the list of usernames and passwords that are registered with the bank.

The application merely takes inputs such as the user types and places it directly into an SQL query constructed to retrieve that user’s information. In PHP that query string would look something like this:

$query = “select accountName, accountNumber from
creditCardAccounts where username='”.$_POST[“username”].”'
and password='”.$_POST[“password”].”'”

Let’s take a look at a browser sending malicious input to a server.

string query = "SELECT * FROM users WHERE username = "'" + username + "' AND
password = '" + password + "'"; 

"joe" as the username and "example' OR 'a'='a as the password, the resulting query
SELECT * FROM users WHERE username = 'joe' AND password = 'example' OR
The "OR 'a'='a' clause always evaluates to true and the intended authentication check is bypassed as a result.

Here we create a Login page in HTML and inject an SQL Injections into an application.

In your Index.html page, input the following code. Save and Close.

<!DOCTYPE html>
  <link rel="stylesheet" type="text/css" href="style.css">

<form action="/login" method="post">
  <div class="container">
    <input type="text" placeholder="Enter Username" name="username" required>

    <input type="password" placeholder="Enter Password" name="password" required>
    <button type="submit">Login</button>

    if(document.location.hash === '#unauthorized') {
        document.write('<div class="unauthorized">Invalid Username or Password</div>');
    } else if(document.location.hash === '#error') {
        document.write('<div class="error">An error has occured</div>');


Now we will create a style.css file, which will include the following code.

form {
    border: 3px solid #f1f1f1;

input[type=text], input[type=password] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;

button {
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;

button:hover {
    opacity: 0.8;

.cancelbtn {
    width: auto;
    padding: 10px 18px;
    background-color: #f44336;

.imgcontainer {
    text-align: center;
    margin: 24px 0 12px 0;

img.avatar {
    width: 40%;
    border-radius: 50%;

.container {
    padding: 16px;

span.psw {
    float: right;
    padding-top: 16px;

.unauthorized {
    background-color: blue;

.error {
    background-color: yellow;

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
    span.psw {
       display: block;
       float: none;
    .cancelbtn {
       width: 100%;

<strong>Create a Run.sh and add the following code:</strong>
<pre class="lang:default decode:true " >node app.js &amp;
echo "CG&gt; success true"
echo "CG&gt; open -p 3000 /index.html"
sleep 1000  

Create an app.js file and add the following code

// { autofold
var express = require('express');
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3').verbose();

var app = express();
app.use(bodyParser.urlencoded({extended: true}));

var db = new sqlite3.Database(':memory:');
db.serialize(function() {
  db.run("CREATE TABLE user (username TEXT, password TEXT, name TEXT)");
  db.run("INSERT INTO user VALUES ('admin', 'admin123', 'App Administrator')");
// }
app.post('/login', function (req, res) {
    var username = req.body.username; // a valid username is admin
    var password = req.body.password; // a valid password is admin123
    var query = "SELECT name FROM user where username = '" + username + "' and password = '" + password + "'";

    console.log("username: " + username);
    console.log("password: " + password);
    console.log('query: ' + query);
    db.get(query , function(err, row) {

        if(err) {
            console.log('ERROR', err);
        } else if (!row) {
        } else {
            res.send('Hello <b>' + row.name + '</b><br /><a href="/index.html">Go back to login</a>');


Output –
The User can Enter the Valid Username and Password. (Username: admin Password-admin123)

Valid Username and Password

The user can login Successfully with the Valid Username and Password.

Now, if you want to inject an SQL Query in the app. All you need to do is the change the password query in the app.js file code with unknown ‘ or ‘1’=’1 in and leave the same username – admin.

inject an SQL Query

admin password

Now, using the password, they can successfully login to the administrator account.

Successful login

Here are a few steps that website owners can do to prevent an SQL injection.

Trust no one: The all user-submitted data is evil so use input validation via a function such as MySQL’s mysql_real_escape_string() to ensure that any malicious characters and input such as ‘ are not passed to a SQL query in data. You should also check everything by filtering user data by context.

Continue To Update and Patches: Vulnerabilities and thread in applications and databases that hackers can exploit using SQL injection are regularly discovered, so it’s vital to apply patches and updates as soon as possible.

Use Firewall: Consider a web application firewall (WAF) – either software or appliance-based – to help filter out malicious data. Good ones will have a comprehensive set of default rules, and make it easy to add new ones whenever necessary. A WAF can be particularly useful to provide some security protection against a new vulnerability before a patch is available.

Buy Better Software: Users should buy a good quality and secure software. Such as Licence Full Version. And privacy protected. from the Authorise vendor. And parties.

Some basic practices you can follow to prevent such situations are:

  • Set strong passwords and don’t share them with anyone
  • Check the privacy settings of your social profile and make sure that you’ve enabled the setting that prevents unconnected people from viewing your details or downloading your images
  • Never share sensitive details like your phone number, address or email address on your social profile, and if you do, make sure that they are hidden from the public
  • Don’t engage with strangers, no matter how familiar they seem
  • Censor yourself while posting via your social profiles
  • Accept requests only from known users

We hope that this guide has been helpful for you guys to learn how hackers can use SQL injection on a particular website to exploit a database. and how users can prevent them.


Please enter your comment!
Please enter your name here