delete()
public function delete(int $id, string $table): bool
Description
Deletes a specific record from a database table based on its ID. This method validates table existence, constructs a parameterized DELETE query, and uses prepared statements to prevent SQL injection. Returns true if the delete operation executes successfully.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| id | int | The ID of the record to delete. | - | Yes |
| table | string | The name of the database table to delete from. | - | Yes |
Return Value
| Type | Description |
|---|---|
| bool | Returns true if the delete query executes successfully, false otherwise. |
Exceptions
- RuntimeException - If the specified table does not exist in the database.
- PDOException - If there's a database error during query execution.
Example #1: Deleting a User Record
The code sample below demonstrates how to delete a user record with ID 15 from the 'users' table.
PHP
$user_id = 15;
$success = $this->db->delete($user_id, 'users');
if ($success) {
echo "User with ID " . $user_id . " has been deleted.";
} else {
echo "Failed to delete user.";
}Example #2: Deleting a Product Record
The code sample below demonstrates how to delete a product from the 'products' table and handle the result.
PHP
$product_id = 42;
$table = 'products';
$deleted = $this->db->delete($product_id, $table);
if ($deleted) {
echo "Product #" . $product_id . " has been removed from the " . $table . " table.";
} else {
echo "Could not delete product #" . $product_id . ".";
}Example #3: Deleting a Record with Error Handling
The code sample below demonstrates how to use try-catch when deleting a record to handle potential exceptions.
PHP
try {
$order_id = 1001;
$result = $this->db->delete($order_id, 'orders');
if ($result) {
echo "Order #" . $order_id . " deleted successfully.";
} else {
echo "Delete operation completed but may not have affected any rows.";
}
} catch (RuntimeException $e) {
echo "Error: " . $e->getMessage();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}Important Notes
- Both parameters (
$idand$table) are required. - The method validates that the table exists before executing the DELETE query.
- Uses prepared statements with parameter binding (:id) for security against SQL injection.
- Returns true if the query executes successfully, even if no rows were actually deleted (e.g., if ID doesn't exist).
- The table name in the SQL query is enclosed in backticks for safety.
- Only deletes records where the primary key column is named 'id'.
- If debug mode is enabled, the generated SQL query will be displayed before execution.
- This operation is permanent - deleted records cannot be recovered through this method.
- Consider implementing soft deletes (using a 'deleted' flag) instead of physical deletion for important data.