Skip to content

Learn online at your pace

Cloud & Security • November 29, 2026 • 8 min read

SQL Injection Explained: How Attacks Work and How to Stop Them

The Qtec Mastery

Author

SQL Injection Explained: How Attacks Work and How to Stop Them

Many hacked websites were not broken by clever malware. They were broken because a form passed what the user typed straight into a database query. SQL injection is one of the oldest web security problems and it still turns up in school portals, shop dashboards and SACCO systems. This guide is for PHP and Laravel developers who want to understand why it happens and how to make their own code safe, step by step.

SQL injection happens when user input is joined directly into an SQL query, so the database treats part of that input as SQL code. The fix is to use prepared statements (parameterised queries), which always keep the query and the data separate.

What is SQL injection?

Your application builds SQL queries to talk to the database. If it builds them by gluing strings together, for example "... WHERE phone = '" . $phone . "'", then whatever the user types becomes part of the SQL itself.

Most users type a phone number. But if someone types characters that SQL understands, such as a quote mark, they can change what the query means. The database cannot tell the difference between the SQL you wrote and the SQL the user slipped in. It just runs the final string.

The consequences can include:

  • Reading records the user should never see, such as every student's phone number.
  • Logging in without a valid password.
  • Changing or deleting data, depending on the database user's permissions.

We will look at the vulnerable pattern only so you can recognise it in your own code. Only test applications you own or have written permission to test. Testing other people's systems without permission is illegal in Kenya under the Computer Misuse and Cybercrimes Act, 2018.

What does vulnerable code look like?

Imagine a small "find my record" page on a college portal. A student enters their phone number and sees their name. It uses the students table from our SQL for beginners examples:

<?php
// VULNERABLE: do not use this pattern
$phone = $_GET['phone'];

$sql = "SELECT student_id, full_name, county
        FROM students
        WHERE phone = '" . $phone . "'";

$result = $pdo->query($sql);

foreach ($result as $row) {
    echo htmlspecialchars($row['full_name']) . '<br>';
}

When Wanjiku types +254712345678, the database receives a perfectly normal query:

SELECT student_id, full_name, county
FROM students
WHERE phone = '+254712345678';

She sees one row: her own.

Why does ' OR '1'='1 work?

Now suppose someone types this into the phone box instead:

' OR '1'='1

The PHP code glues it in, and the database receives:

SELECT student_id, full_name, county
FROM students
WHERE phone = '' OR '1'='1';

Look at what happened. The first quote in the input closed the phone string early. The rest became real SQL. The condition now says "phone is empty or 1 equals 1", and since '1'='1' is true for every row, the database returns every student:

student_idfull_namecounty
1Wanjiku KamauNairobi
2Brian OtienoKisumu
3Amina HassanMombasa
4Kevin MutuaMachakos
5Faith ChebetUasin Gishu

The same trick against a login query that checks a username and password in one WHERE clause can make the condition true without a correct password. The root cause is always the same: data was allowed to become code.

Escaping quotes by hand, or blocking words like OR, is not a reliable fix. There are too many edge cases. The real fix changes how the query is sent.

How do prepared statements stop SQL injection?

A prepared statement sends the database the query shape first, with placeholders where the values go. The values are sent separately. The database already knows the structure of the query, so the values can only ever be treated as data, never as SQL.

Prepared statements in PHP PDO

<?php
$pdo = new PDO(
    'mysql:host=localhost;dbname=school;charset=utf8mb4',
    $dbUser,
    $dbPass,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

$phone = $_GET['phone'] ?? '';

$stmt = $pdo->prepare(
    'SELECT student_id, full_name, county
     FROM students
     WHERE phone = :phone'
);
$stmt->execute(['phone' => $phone]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

Now if someone types ' OR '1'='1, the database simply looks for a student whose phone number is literally that text. There is none, so nothing is returned. The attack becomes a harmless search.

Two settings in that connection matter. ERRMODE_EXCEPTION makes errors throw exceptions so you can handle them properly, and turning off emulated prepares makes PDO use MySQL's native prepared statements.

Laravel's query builder and Eloquent

Laravel uses PDO parameter binding under the hood, so normal query builder and Eloquent calls are safe:

// Query builder
$student = DB::table('students')->where('phone', $phone)->first();

// Eloquent
$student = Student::where('phone', $phone)->first();

// Raw SQL: still bind the values
$students = DB::select('SELECT * FROM students WHERE county = ?', [$county]);
$students = Student::whereRaw('county = ?', [$county])->get();

The danger in Laravel comes from raw methods with values glued in, such as whereRaw("county = '$county'") or DB::raw() built from user input. If you see a variable inside a raw SQL string, treat it as a bug.

What about column names and sort order?

Placeholders work for values, not for table or column names. If users can choose a sort column, check it against an allowlist:

$allowed = ['full_name', 'county', 'enrolled_on'];
$sort = in_array($_GET['sort'] ?? '', $allowed, true) ? $_GET['sort'] : 'full_name';

$stmt = $pdo->prepare("SELECT full_name, county FROM students ORDER BY $sort");
$stmt->execute();

Why should the database user have limited permissions?

Prepared statements are the main fix. Least privilege is your safety net if a mistake slips through. Your web app should not connect as root. Create a dedicated MySQL user with only the permissions the app needs:

CREATE USER 'portal_app'@'localhost' IDENTIFIED BY 'use-a-long-random-password';

GRANT SELECT, INSERT, UPDATE ON school.students TO 'portal_app'@'localhost';
GRANT SELECT ON school.courses TO 'portal_app'@'localhost';
GRANT SELECT, INSERT ON school.payments TO 'portal_app'@'localhost';

This user cannot drop tables, cannot delete payment records and cannot touch other databases on the server. If an injection bug ever existed, the damage would be far more limited.

Is input validation enough on its own?

No, but it is a valuable second layer. Validation checks that input looks the way it should before you use it. A Kenyan phone number, for example, should match a simple pattern:

if (!preg_match('/^(\+254|0)[17]\d{8}$/', $phone)) {
    http_response_code(422);
    exit('Please enter a valid Kenyan phone number.');
}

In Laravel you would write $request->validate(['phone' => ['required', 'regex:/^(\+254|0)[17]\d{8}$/']]).

Validation improves data quality and blocks a lot of junk, but some fields, such as names and comments, legitimately contain quotes (think of O'Brien). That is why validation supports prepared statements and never replaces them. Also avoid showing raw database errors to users: log them on the server and show a friendly message instead.

What does Kenya's Data Protection Act say about this?

Names, phone numbers and payment records are personal data. Kenya's Data Protection Act, 2019 requires organisations that handle personal data to protect it with appropriate technical and organisational safeguards. The Office of the Data Protection Commissioner (ODPC) enforces the Act, and data breaches must be reported to the Commissioner.

A leaked student list from an SQL injection bug is exactly the kind of breach the Act is concerned with. Writing safe queries is not only good engineering, it is part of meeting your legal duties to the people whose data you hold. Pair this with storing credentials correctly, covered in How to Store Passwords Safely.

Common mistakes developers make

  • Using prepared statements in some places only. One concatenated query is enough to cause a breach. Search your code for ->query( and raw SQL with variables inside.
  • Trusting hidden fields, cookies or API data. Anything that comes from outside your server can be changed.
  • Relying on JavaScript validation. It helps users but anyone can bypass it.
  • Connecting as root. Use a least-privilege user.
  • Showing SQL errors on screen. They reveal table and column names.

If you want to go further into web security as a career, our guide to the cyber security course in Kenya explains where to start.

Learn to build and defend secure systems

Cyber Security Fundamentals is a 6-week online course (KES 15,000) for developers and beginners who want to understand common attacks and how to defend against them.

See the course →

Also useful: Data Protection & Privacy (4 weeks, KES 5,000)

Frequently asked questions

Is SQL injection still a problem today?

Yes. Modern frameworks make safe queries the default, but injection still appears in older code, quick scripts and anywhere developers build raw SQL from user input.

Does mysqli also support prepared statements?

Yes. mysqli supports prepared statements with prepare() and bind_param(), and since PHP 8.1 you can pass values to execute(). PDO is often preferred because it works with several databases.

Is Laravel safe from SQL injection by default?

The query builder and Eloquent bind values for you. You can still create a hole by putting user input inside raw methods like whereRaw or DB::raw without bindings.

Does escaping with addslashes() prevent SQL injection?

Do not rely on it. Hand-made escaping misses edge cases. Use prepared statements instead.

Comments (0)

Comments appear after a quick review. Your email is never shown.

You Might Also Like

How to Store Passwords Safely: Hashing, Salting and bcrypt Explained

How to Store Passwords Safely: Hashing, Salting and bcrypt Explained

If your app has a login page, you are responsible for every password your users...

Read More →
Cyber Security Course in Kenya: What It's All About, Fees and Where to Start

Cyber Security Course in Kenya: What It's All About, Fees and Where to Start

"Cyber security course in Kenya" is one of the most searched tech courses in the...

Read More →