Bird
Raised Fist0
PHPprogramming~20 mins

How SQL injection exploits unsafe queries in PHP - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
SQL Injection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code with unsafe SQL query?

Consider this PHP code snippet that builds an SQL query unsafely using user input. What will be the output when the input is admin' -- ?

PHP
<?php
$user_input = "admin' -- ";
$query = "SELECT * FROM users WHERE username = '$user_input'";
echo $query;
?>
ASELECT * FROM users WHERE username = 'admin'' -- '
BSELECT * FROM users WHERE username = 'admin' --
CSELECT * FROM users WHERE username = 'admin -- '
DSELECT * FROM users WHERE username = 'admin\' -- '
Attempts:
2 left
💡 Hint

Look carefully at how the input is inserted directly into the query string.

🧠 Conceptual
intermediate
2:00remaining
Which part of this SQL query is vulnerable to injection?

Given this PHP code snippet, which part is the main cause of SQL injection vulnerability?

$query = "SELECT * FROM users WHERE username = '" . $_GET['user'] . "'";
AConcatenating user input directly into the query
BUsing double quotes for the query string
CUsing single quotes around the username
DNot using a semicolon at the end of the query
Attempts:
2 left
💡 Hint

Think about how user input is handled inside the query.

🔧 Debug
advanced
2:00remaining
What error occurs when this unsafe query is executed with input: ' OR 1=1 -- ?

Look at this PHP code snippet. What error or behavior will happen if the input is ' OR 1=1 -- ?

$input = "' OR 1=1 -- ";
$sql = "SELECT * FROM users WHERE username = '$input'";
$result = mysqli_query($conn, $sql);
APHP fatal error due to undefined variable
BSyntax error in SQL query
CEmpty result set returned
DThe query returns all rows from the users table
Attempts:
2 left
💡 Hint

Consider what the injected SQL code does inside the WHERE clause.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this unsafe SQL query?

Given this PHP code snippet, which option will cause a syntax error when executed?

$input = $_GET['input'];
$sql = "SELECT * FROM users WHERE username = '$input'";
Ainput = admin'; DROP TABLE users; --
Binput = admin" OR 1=1 --
Cinput = admin
Dinput = admin' OR '1'='1
Attempts:
2 left
💡 Hint

Look at how quotes are used and closed in the query string.

🚀 Application
expert
3:00remaining
How can an attacker exploit this unsafe query to bypass login?

Given this PHP login code snippet, how can an attacker craft the username input to bypass password verification?

$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
  echo 'Login successful';
} else {
  echo 'Login failed';
}
Ausername = admin' -- , password = anything
Busername = admin, password = ' OR '1'='1
Cusername = admin' OR '1'='1, password = anything
Dusername = admin, password = admin
Attempts:
2 left
💡 Hint

Think about how to make the WHERE clause always true by injecting SQL in username.

Practice

(1/5)
1. What is the main risk of using unsafe SQL queries in PHP without proper input handling?
easy
A. The website will load faster
B. Users will see more colorful pages
C. Attackers can insert harmful SQL commands to access or damage the database
D. The server will automatically block all users

Solution

  1. Step 1: Understand unsafe SQL queries

    Unsafe queries allow user input directly in SQL commands without checks.
  2. Step 2: Identify the risk of SQL injection

    This lets attackers add harmful commands to steal or change data.
  3. Final Answer:

    Attackers can insert harmful SQL commands to access or damage the database -> Option C
  4. Quick Check:

    Unsafe queries = SQL injection risk [OK]
Hint: Unsafe queries let attackers add harmful commands [OK]
Common Mistakes:
  • Thinking unsafe queries improve speed
  • Confusing SQL injection with visual changes
  • Assuming server blocks all users automatically
2. Which PHP code snippet is unsafe and vulnerable to SQL injection?
easy
A. $query = "SELECT * FROM users WHERE name = '" . $_GET['name'] . "'";
B. $stmt = $pdo->prepare('SELECT * FROM users WHERE name = ?'); $stmt->execute([$_GET['name']]);
C. $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name'); $stmt->execute(['name' => $_GET['name']]);
D. $query = 'SELECT * FROM users WHERE name = :name'; $stmt = $pdo->prepare($query); $stmt->execute(['name' => 'Alice']);

Solution

  1. Step 1: Identify direct user input in query string

    $query = "SELECT * FROM users WHERE name = '" . $_GET['name'] . "'"; directly inserts $_GET['name'] into the SQL string without protection.
  2. Step 2: Compare with prepared statements

    Options A, B, and D use prepared statements which safely handle input.
  3. Final Answer:

    $query = "SELECT * FROM users WHERE name = '" . $_GET['name'] . "'"; -> Option A
  4. Quick Check:

    Direct input in query = unsafe [OK]
Hint: Directly adding user input to query is unsafe [OK]
Common Mistakes:
  • Confusing prepared statements with unsafe queries
  • Thinking all string concatenations are safe
  • Ignoring the use of placeholders in queries
3. What will be the output of this PHP code if the URL parameter is ?id=1 OR 1=1?
$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = $id";
echo $query;
medium
A. SELECT * FROM users WHERE id = 1
B. SELECT * FROM users WHERE id = 1 OR 1=1
C. Syntax error in SQL query
D. SELECT * FROM users WHERE id = '1 OR 1=1'

Solution

  1. Step 1: Substitute the URL parameter into the query

    The variable $id becomes the string "1 OR 1=1" directly inserted into the query.
  2. Step 2: Form the final SQL query string

    The query becomes: SELECT * FROM users WHERE id = 1 OR 1=1, which is a valid SQL statement.
  3. Final Answer:

    SELECT * FROM users WHERE id = 1 OR 1=1 -> Option B
  4. Quick Check:

    Unsafe input inserted directly = query with injected condition [OK]
Hint: Direct input inserts raw text into query [OK]
Common Mistakes:
  • Assuming input is automatically quoted
  • Expecting syntax error without quotes
  • Ignoring how SQL interprets OR conditions
4. Identify the error in this PHP code that makes it vulnerable to SQL injection:
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
medium
A. The query string is missing a semicolon
B. The variable $username is not defined
C. mysqli_query cannot run SELECT queries
D. Using prepared statements would prevent SQL injection

Solution

  1. Step 1: Check how user input is used in the query

    The variable $username is inserted directly into the SQL string without sanitization.
  2. Step 2: Suggest the fix to prevent injection

    Using prepared statements safely handles input and prevents injection attacks.
  3. Final Answer:

    Using prepared statements would prevent SQL injection -> Option D
  4. Quick Check:

    Direct input in query = vulnerability [OK]
Hint: Use prepared statements to fix injection bugs [OK]
Common Mistakes:
  • Thinking variable is undefined
  • Believing mysqli_query can't run SELECT
  • Focusing on missing semicolon instead of security
5. You want to fix this vulnerable PHP code to prevent SQL injection:
$email = $_POST['email'];
$query = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $query);
Which is the best way to fix it?
hard
A. $stmt = $conn->prepare('SELECT * FROM users WHERE email = ?'); $stmt->bind_param('s', $email); $stmt->execute();
B. $email = addslashes($_POST['email']); $query = "SELECT * FROM users WHERE email = '$email'"; mysqli_query($conn, $query);
C. $query = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'"; mysqli_query($conn, $query);
D. $email = htmlspecialchars($_POST['email']); $query = "SELECT * FROM users WHERE email = '$email'"; mysqli_query($conn, $query);

Solution

  1. Step 1: Review each option's security

    $stmt = $conn->prepare('SELECT * FROM users WHERE email = ?'); $stmt->bind_param('s', $email); $stmt->execute(); uses prepared statements with parameter binding, which safely handles input.
  2. Step 2: Compare other options

    $email = addslashes($_POST['email']); $query = "SELECT * FROM users WHERE email = '$email'"; mysqli_query($conn, $query); uses addslashes which is not fully safe; C is unsafe direct insertion; D uses htmlspecialchars which is for HTML, not SQL.
  3. Final Answer:

    $stmt = $conn->prepare('SELECT * FROM users WHERE email = ?'); $stmt->bind_param('s', $email); $stmt->execute(); -> Option A
  4. Quick Check:

    Prepared statements = best SQL injection protection [OK]
Hint: Use prepared statements with bind_param for safety [OK]
Common Mistakes:
  • Relying on addslashes for security
  • Using htmlspecialchars for SQL input
  • Continuing direct string concatenation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard