Bird
Raised Fist0
PHPprogramming~20 mins

Insert, update, delete operations in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Insert, Update, Delete
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 insert operation?

Consider the following PHP code that inserts a new user into a database. What will be the output?

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)");
$result = $stmt->execute([':name' => 'Alice']);
echo $result ? 'Insert successful' : 'Insert failed';
?>
AFatal error: Uncaught exception
BInsert successful
CInsert failed
DSyntax error
Attempts:
2 left
💡 Hint

Check if the execute() method returns true on success.

❓ Predict Output
intermediate
2:00remaining
What is the output after this update operation?

This PHP code updates a user's name in the database. What will be the output?

PHP
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);");
$pdo->exec("INSERT INTO users (name) VALUES ('Bob');");
$stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
$success = $stmt->execute([':name' => 'Robert', ':id' => 1]);
echo $success ? $stmt->rowCount() : 0;
?>
ASyntax error
B0
C1
Dfalse
Attempts:
2 left
💡 Hint

rowCount() returns the number of rows affected by the update.

❓ Predict Output
advanced
2:00remaining
What error does this PHP delete operation raise?

Look at this PHP code that tries to delete a user. What error will it produce?

PHP
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);");
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute();
?>
APDOException: SQLSTATE[HY093]: Invalid parameter number
BNo error, deletes all rows
CSyntax error
DFatal error: Missing argument
Attempts:
2 left
💡 Hint

Check if the execute() method is called with the required parameter.

🧠 Conceptual
advanced
2:00remaining
Which option correctly updates multiple rows in PHP?

You want to update the status of all users older than 30 to 'active'. Which PHP code snippet does this correctly?

A$stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE age > 30"); $stmt->execute();
B$stmt = $pdo->prepare("UPDATE users SET status = :status WHERE age > :age"); $stmt->execute(['status' => 'active']);
C$stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE age > 30"); $stmt->execute(['active', 30]);
D$stmt = $pdo->prepare("UPDATE users SET status = :status WHERE age > :age"); $stmt->execute(['active', 30]);
Attempts:
2 left
💡 Hint

Check if the parameters match the placeholders in the query.

❓ Predict Output
expert
3:00remaining
What is the output of this PHP code with transactions?

This PHP code uses a transaction to insert and then delete a user. What will be the output?

PHP
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);");
try {
  $pdo->beginTransaction();
  $pdo->exec("INSERT INTO users (name) VALUES ('Charlie');");
  $pdo->exec("DELETE FROM users WHERE name = 'Charlie';");
  $pdo->commit();
  $count = $pdo->query("SELECT COUNT(*) FROM users;")->fetchColumn();
  echo $count;
} catch (Exception $e) {
  $pdo->rollBack();
  echo 'Failed';
}
?>
ASyntax error
B1
CFailed
D0
Attempts:
2 left
💡 Hint

Think about what happens when you insert and then delete the same row inside a transaction.

Practice

(1/5)
1. Which SQL statement is used in PHP to add new data into a database table?
easy
A. UPDATE
B. INSERT INTO
C. DELETE FROM
D. SELECT

Solution

  1. Step 1: Understand the purpose of each SQL command

    INSERT INTO adds new rows, UPDATE changes existing rows, DELETE FROM removes rows, and SELECT retrieves data.
  2. Step 2: Match the command to adding new data

    Since adding new data means inserting new rows, the correct command is INSERT INTO.
  3. Final Answer:

    INSERT INTO -> Option B
  4. Quick Check:

    Insert = Add new data [OK]
Hint: Insert adds new rows; update and delete modify existing ones [OK]
Common Mistakes:
  • Confusing UPDATE with INSERT
  • Thinking DELETE adds data
  • Using SELECT to add data
2. Which of the following is the correct PHP syntax to update a user's email in a MySQL database using mysqli_query?
easy
A. $sql = "DELETE FROM users SET email = 'new@example.com' WHERE id = 1";
B. $sql = "INSERT INTO users email = 'new@example.com' WHERE id = 1";
C. $sql = "SELECT email = 'new@example.com' FROM users WHERE id = 1";
D. $sql = "UPDATE users SET email = 'new@example.com' WHERE id = 1";

Solution

  1. Step 1: Identify the correct SQL syntax for updating

    The correct syntax for updating is UPDATE table SET column = value WHERE condition.
  2. Step 2: Check each option's syntax

    $sql = "UPDATE users SET email = 'new@example.com' WHERE id = 1"; matches the correct syntax. Options A, B, and D misuse SQL commands or syntax.
  3. Final Answer:

    $sql = "UPDATE users SET email = 'new@example.com' WHERE id = 1"; -> Option D
  4. Quick Check:

    Update syntax = UPDATE ... SET ... WHERE ... [OK]
Hint: Update uses SET with WHERE to change specific rows [OK]
Common Mistakes:
  • Using INSERT syntax for update
  • Omitting WHERE clause in update
  • Using DELETE or SELECT instead of UPDATE
3. What will be the output of the following PHP code snippet?
$conn = new mysqli('localhost', 'user', 'pass', 'db');
$sql = "DELETE FROM products WHERE id = 10";
if ($conn->query($sql) === TRUE) {
    echo "Deleted successfully";
} else {
    echo "Error deleting record";
}
medium
A. No output
B. Error deleting record
C. Deleted successfully
D. Syntax error

Solution

  1. Step 1: Understand the code logic

    The code tries to delete a product with id 10. If the query runs without error, it prints "Deleted successfully".
  2. Step 2: Assume the query runs correctly

    Since the SQL syntax is correct and connection is assumed valid, the query returns TRUE, so the success message prints.
  3. Final Answer:

    Deleted successfully -> Option C
  4. Quick Check:

    Successful DELETE query prints success message [OK]
Hint: If query returns TRUE, success message prints [OK]
Common Mistakes:
  • Assuming syntax error without checking code
  • Confusing TRUE with FALSE return values
  • Ignoring the if-else structure
4. Identify the error in this PHP code that tries to update a user's name:
$sql = "UPDATE users SET name = 'John'";
$conn->query($sql);
medium
A. Missing WHERE clause to specify which user to update
B. Incorrect SQL keyword, should be INSERT
C. Quotes around 'John' should be double quotes
D. Missing semicolon after query execution

Solution

  1. Step 1: Review the SQL update statement

    The statement updates the name but does not specify which row to update because it lacks a WHERE clause.
  2. Step 2: Understand the impact of missing WHERE

    Without WHERE, all rows in the table will be updated, which is usually unintended and considered an error.
  3. Final Answer:

    Missing WHERE clause to specify which user to update -> Option A
  4. Quick Check:

    Update without WHERE affects all rows [OK]
Hint: Always include WHERE in update to target specific rows [OK]
Common Mistakes:
  • Thinking quotes type causes error
  • Confusing UPDATE with INSERT
  • Ignoring missing WHERE consequences
5. You want to delete all users from the users table who have not logged in for over a year. Which PHP code snippet correctly performs this operation assuming the last login date is stored in last_login column?
hard
A. $sql = "DELETE FROM users WHERE last_login < DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql);
B. $sql = "UPDATE users SET last_login = NULL WHERE last_login > DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql);
C. $sql = "DELETE FROM users WHERE last_login > DATE_ADD(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql);
D. $sql = "INSERT INTO users (last_login) VALUES (DATE_SUB(NOW(), INTERVAL 1 YEAR))"; $conn->query($sql);

Solution

  1. Step 1: Understand the condition for deletion

    We want to delete users whose last_login is older than one year, so the condition is last_login < DATE_SUB(NOW(), INTERVAL 1 YEAR).
  2. Step 2: Check each option's SQL logic

    $sql = "DELETE FROM users WHERE last_login < DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql); correctly deletes users with last login older than one year. $sql = "UPDATE users SET last_login = NULL WHERE last_login > DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql); updates instead of deletes. $sql = "DELETE FROM users WHERE last_login > DATE_ADD(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql); deletes users with last login in the future, which is wrong. $sql = "INSERT INTO users (last_login) VALUES (DATE_SUB(NOW(), INTERVAL 1 YEAR))"; $conn->query($sql); inserts new rows, which is incorrect.
  3. Final Answer:

    $sql = "DELETE FROM users WHERE last_login < DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql); -> Option A
  4. Quick Check:

    Delete with condition older than 1 year = $sql = "DELETE FROM users WHERE last_login < DATE_SUB(NOW(), INTERVAL 1 YEAR)"; $conn->query($sql); [OK]
Hint: Use DELETE with WHERE and DATE_SUB for time conditions [OK]
Common Mistakes:
  • Using UPDATE instead of DELETE
  • Wrong date comparison operators
  • Using INSERT instead of DELETE
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