Bird
Raised Fist0
PHPprogramming~20 mins

Prepared statements and why they matter in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prepared Statements Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a prepared statement execution
What will be the output of this PHP code using a prepared statement?
PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$stmt = $mysqli->prepare('SELECT name FROM users WHERE id = ?');
$id = 2;
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($name);
$stmt->fetch();
echo $name;
?>
AAn error because bind_param is missing a parameter
BThe name of the user with id 2
CEmpty output because fetch() was not called
DThe string 'id' printed instead of the name
Attempts:
2 left
💡 Hint
Remember that bind_param binds the variable by reference and fetch() retrieves the result.
🧠 Conceptual
intermediate
1:30remaining
Why use prepared statements?
Which of the following is the main reason to use prepared statements in PHP when working with databases?
AThey prevent SQL injection by separating code from data
BThey allow queries to run without a database connection
CThey automatically cache query results for faster access
DThey format the output of queries into JSON automatically
Attempts:
2 left
💡 Hint
Think about security and how user input is handled.
🔧 Debug
advanced
2:00remaining
Identify the error in this prepared statement code
What error will this PHP code produce when executed?
PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$stmt = $mysqli->prepare('INSERT INTO users (name, age) VALUES (?, ?)');
$name = 'Alice';
$age = 'twenty';
$stmt->bind_param('si', $name, $age);
$stmt->execute();
?>
ATypeError because 'twenty' is not an integer
BNo error, the data is inserted successfully
CSyntaxError due to wrong SQL syntax
DRuntime error because bind_param expects variables passed by reference
Attempts:
2 left
💡 Hint
Check the types expected by bind_param and the actual variable types.
📝 Syntax
advanced
1:30remaining
Which prepared statement code is syntactically correct?
Which option shows a syntactically correct way to prepare and execute a statement in PHP?
A
$stmt = $mysqli-&gt;prepare('SELECT * FROM users WHERE id = ?')
$stmt-&gt;bind_param('i', $id)
$stmt-&gt;execute()
B
$stmt = $mysqli-&gt;prepare('SELECT * FROM users WHERE id = ?');
$stmt-&gt;bind_param('i' $id);
$stmt-&gt;execute();
C
$stmt = $mysqli-&gt;prepare('SELECT * FROM users WHERE id = ?');
$stmt-&gt;bind_param(i, $id);
$stmt-&gt;execute();
D
$stmt = $mysqli-&gt;prepare('SELECT * FROM users WHERE id = ?');
$stmt-&gt;bind_param('i', $id);
$stmt-&gt;execute();
Attempts:
2 left
💡 Hint
Check for missing semicolons and correct quotes around types.
🚀 Application
expert
2:30remaining
How many rows will be returned?
Given this PHP code using prepared statements, how many rows will be returned by the query?
PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$stmt = $mysqli->prepare('SELECT * FROM users WHERE age > ?');
$age_limit = 30;
$stmt->bind_param('i', $age_limit);
$stmt->execute();
$result = $stmt->get_result();
echo $result->num_rows;
?>
AAn error because get_result() is not supported
BAll users regardless of age
CZero, because $age_limit is not defined with $
DThe number of users older than 30
Attempts:
2 left
💡 Hint
Check variable naming carefully.

Practice

(1/5)
1. What is the main reason to use prepared statements in PHP when working with databases?
easy
A. To protect the database from SQL injection attacks
B. To make the code run faster by skipping queries
C. To store data permanently in variables
D. To automatically create database tables

Solution

  1. Step 1: Understand the purpose of prepared statements

    Prepared statements separate SQL code from user data, preventing malicious input from changing the query.
  2. Step 2: Identify the security benefit

    This separation protects against SQL injection, a common hacking method.
  3. Final Answer:

    To protect the database from SQL injection attacks -> Option A
  4. Quick Check:

    Security = Protect from SQL injection [OK]
Hint: Prepared statements stop hackers from changing your queries [OK]
Common Mistakes:
  • Thinking prepared statements speed up queries significantly
  • Confusing prepared statements with data storage
  • Believing prepared statements create tables automatically
2. Which of the following is the correct syntax to prepare a statement using PDO in PHP?
easy
A. $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
B. $stmt = $pdo->query('SELECT * FROM users WHERE id = ?');
C. $stmt = $pdo->execute('SELECT * FROM users WHERE id = ?');
D. $stmt = $pdo->fetch('SELECT * FROM users WHERE id = ?');

Solution

  1. Step 1: Recall PDO method for preparing statements

    The correct method to prepare a statement is prepare(), which sets up the SQL with placeholders.
  2. Step 2: Check the options for correct method usage

    Only $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); uses prepare() correctly with a SQL string containing a placeholder.
  3. Final Answer:

    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); -> Option A
  4. Quick Check:

    PDO prepare() method = $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); [OK]
Hint: Use prepare() to set up SQL with placeholders [OK]
Common Mistakes:
  • Using query() instead of prepare() for statements with placeholders
  • Trying to execute SQL directly with execute() without preparing
  • Confusing fetch() with prepare()
3. What will be the output of the following PHP code snippet?
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (id INTEGER, name TEXT)');
$stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (?, ?)');
$stmt->execute([1, 'Alice']);
$stmt->execute([2, 'Bob']);
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = ?');
$stmt->execute([2]);
echo $stmt->fetchColumn();
medium
A. 1
B. Alice
C. Bob
D. Error

Solution

  1. Step 1: Insert two users into the table

    The code inserts two rows: id=1 with name 'Alice' and id=2 with name 'Bob'.
  2. Step 2: Select the name where id = 2

    The prepared statement selects the name for id=2, which is 'Bob'.
  3. Final Answer:

    Bob -> Option C
  4. Quick Check:

    Selected name for id=2 = Bob [OK]
Hint: Check which id is queried to find the correct name [OK]
Common Mistakes:
  • Confusing the order of inserted rows
  • Expecting the first inserted name instead of the queried one
  • Assuming an error due to missing database file
4. Identify the error in the following PHP code using prepared statements:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute('user@example.com');
$result = $stmt->fetchAll();
medium
A. The SQL query is missing a WHERE clause
B. The prepare() method is missing a placeholder
C. fetchAll() cannot be used after execute()
D. The execute() method should receive an array, not a string

Solution

  1. Step 1: Check the execute() method argument

    When using named placeholders like ':email', execute() expects an associative array with keys matching placeholders.
  2. Step 2: Identify the incorrect argument type

    The code passes a string directly instead of an array like ['email' => 'user@example.com'].
  3. Final Answer:

    The execute() method should receive an array, not a string -> Option D
  4. Quick Check:

    execute() needs array for named placeholders [OK]
Hint: Pass an array to execute() when using named placeholders [OK]
Common Mistakes:
  • Passing a string instead of an array to execute()
  • Forgetting to match placeholder names in the array keys
  • Thinking fetchAll() cannot follow execute()
5. You want to insert multiple user records safely using prepared statements in PHP. Which approach below correctly uses prepared statements to insert two users with ids and names?
hard
A. $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (?, ?)'); $stmt->execute(1, 'Alice'); $stmt->execute(2, 'Bob');
B. $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice']); $stmt->execute(['id' => 2, 'name' => 'Bob']);
C. $pdo->exec("INSERT INTO users (id, name) VALUES (1, 'Alice'), (2, 'Bob')");
D. $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice', 'id' => 2, 'name' => 'Bob']);

Solution

  1. Step 1: Understand how to use named placeholders for multiple inserts

    Using named placeholders (:id, :name) allows binding values clearly for each execute call.
  2. Step 2: Check each option for correct usage

    Only $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice']); $stmt->execute(['id' => 2, 'name' => 'Bob']); correctly prepares once and executes twice with separate associative arrays for each user.
  3. Step 3: Identify errors in other options

    $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (?, ?)'); $stmt->execute(1, 'Alice'); $stmt->execute(2, 'Bob'); incorrectly passes parameters directly to execute() without an array; $pdo->exec("INSERT INTO users (id, name) VALUES (1, 'Alice'), (2, 'Bob')"); uses exec() without preparing; $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice', 'id' => 2, 'name' => 'Bob']); tries to pass multiple users in one execute call incorrectly.
  4. Final Answer:

    $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice']); $stmt->execute(['id' => 2, 'name' => 'Bob']); -> Option B
  5. Quick Check:

    Named placeholders + separate execute calls = $stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (:id, :name)'); $stmt->execute(['id' => 1, 'name' => 'Alice']); $stmt->execute(['id' => 2, 'name' => 'Bob']); [OK]
Hint: Use named placeholders and separate execute() calls per record [OK]
Common Mistakes:
  • Passing multiple records in one execute call incorrectly
  • Not using prepared statements and risking SQL injection
  • Passing parameters to execute() without an array for positional placeholders
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