A prepared statement is a feature that lets you write a SQL query template with placeholders. You fill in the placeholders later with actual values before running the query. This helps keep your database safe and your code efficient.
Click to reveal answer
beginner
Why do prepared statements help prevent SQL injection?
Prepared statements separate the SQL code from the data. This means user input is treated only as data, not as part of the SQL command. So, attackers cannot change the query by injecting harmful SQL code.
Click to reveal answer
intermediate
How do prepared statements improve performance?
The database server compiles the SQL query once, then runs it many times with different data. This saves time because the server doesn’t have to parse and plan the query each time.
Click to reveal answer
beginner
Show a simple PHP example of using a prepared statement to select a user by ID.
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch();
Click to reveal answer
beginner
What happens if you don’t use prepared statements and insert user input directly into SQL?
If you insert user input directly, attackers can add SQL code that changes your query. This can lead to data leaks, data loss, or unauthorized access. This is called SQL injection.
Click to reveal answer
What is the main security benefit of using prepared statements?
AThey make the website load faster
BThey prevent SQL injection attacks
CThey allow multiple users to connect at once
DThey automatically encrypt data
✗ Incorrect
Prepared statements keep SQL code and data separate, stopping attackers from injecting harmful SQL.
In PHP, which method prepares a SQL statement for execution?
A$pdo->execute()
B$pdo->query()
C$pdo->fetch()
D$pdo->prepare()
✗ Incorrect
The prepare() method creates a prepared statement with placeholders.
What symbol is commonly used as a placeholder in prepared statements?
A#
B&
C?
D$
✗ Incorrect
The question mark (?) is used as a placeholder for values in prepared statements.
Which of these is NOT a benefit of prepared statements?
AAutomatic data encryption
BImproved security
CBetter performance
DCleaner code
✗ Incorrect
Prepared statements do not encrypt data automatically.
What happens if you execute a prepared statement multiple times with different data?
AThe query runs faster because it’s compiled once
BThe database recompiles the query each time
CThe query fails after the first execution
DThe data is ignored
✗ Incorrect
Prepared statements compile the query once, so running it multiple times with new data is faster.
Explain in your own words why prepared statements are important for database security.
Think about how attackers try to change SQL queries.
You got /3 concepts.
Describe the steps to use a prepared statement in PHP to safely query a database.
Remember the order: prepare, execute, fetch.
You got /4 concepts.
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
Step 1: Understand the purpose of prepared statements
Prepared statements separate SQL code from user data, preventing malicious input from changing the query.
Step 2: Identify the security benefit
This separation protects against SQL injection, a common hacking method.
Final Answer:
To protect the database from SQL injection attacks -> Option A
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
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
Step 1: Recall PDO method for preparing statements
The correct method to prepare a statement is prepare(), which sets up the SQL with placeholders.
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.
Final Answer:
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); -> Option A
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
Step 1: Insert two users into the table
The code inserts two rows: id=1 with name 'Alice' and id=2 with name 'Bob'.
Step 2: Select the name where id = 2
The prepared statement selects the name for id=2, which is 'Bob'.
Final Answer:
Bob -> Option C
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
Step 1: Check the execute() method argument
When using named placeholders like ':email', execute() expects an associative array with keys matching placeholders.
Step 2: Identify the incorrect argument type
The code passes a string directly instead of an array like ['email' => 'user@example.com'].
Final Answer:
The execute() method should receive an array, not a string -> Option D
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');
Step 1: Understand how to use named placeholders for multiple inserts
Using named placeholders (:id, :name) allows binding values clearly for each execute call.
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.
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.