Challenge - 5 Problems
Prepared Statements Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of prepared statement execution
What will be the output of this PHP code snippet when executed successfully?
PHP
<?php $pdo = new PDO('sqlite::memory:'); $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)'); $stmt = $pdo->prepare('INSERT INTO users (name) VALUES (:name)'); $stmt->execute([':name' => 'Alice']); $stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id'); $stmt->execute([':id' => 1]); $result = $stmt->fetchColumn(); echo $result; ?>
Attempts:
2 left
💡 Hint
Look at what value is inserted and then selected by id.
✗ Incorrect
The code inserts 'Alice' into the users table with id 1, then selects the name where id=1, so it outputs 'Alice'.
🧠 Conceptual
intermediate1:30remaining
Why use prepared statements?
Which of the following best explains why prepared statements help prevent SQL injection?
Attempts:
2 left
💡 Hint
Think about how user input is handled differently with prepared statements.
✗ Incorrect
Prepared statements keep the SQL code fixed and treat user input only as data, preventing attackers from injecting SQL commands.
🔧 Debug
advanced2:00remaining
Identify the error in prepared statement usage
What error will this PHP code produce when executed?
PHP
<?php $pdo = new PDO('sqlite::memory:'); $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)'); $stmt = $pdo->prepare('INSERT INTO users (name) VALUES (?)'); $stmt->execute(['name' => 'Bob']); ?>
Attempts:
2 left
💡 Hint
Check how parameters are passed for positional placeholders.
✗ Incorrect
The prepared statement uses positional placeholders (?), but the execute array uses named keys, causing a parameter mismatch error.
📝 Syntax
advanced1:30remaining
Correct syntax for named placeholders
Which option shows the correct way to prepare and execute a statement with named placeholders in PHP PDO?
Attempts:
2 left
💡 Hint
Named placeholders require the colon in the execute array keys.
✗ Incorrect
When using named placeholders, the keys in the execute array must include the colon prefix to match the placeholder names.
🚀 Application
expert3:00remaining
Preventing injection in dynamic queries
You want to select users by either 'id' or 'email' depending on user input. Which code snippet safely uses prepared statements to prevent SQL injection?
Attempts:
2 left
💡 Hint
Think about how to avoid injecting the column name directly from user input.
✗ Incorrect
Option B uses fixed SQL with placeholders only for values, never injecting user input into SQL structure. Options A and D inject $filter or mix parameters incorrectly. Option B searches both columns regardless of filter.