← Back to Chapters

PHP CRUD Class – Delete Method

?️ PHP CRUD Class – Delete Method

? Quick Overview

The Delete method in a PHP CRUD class is responsible for permanently removing records from a database using secure prepared statements. It ensures controlled deletion while maintaining clean and reusable object-oriented code.

? Key Concepts

  • Prepared statements for SQL safety
  • Using primary keys for deletion
  • Checking affected rows after execution
  • Encapsulation inside a CRUD class

? Syntax & Theory

The delete method typically accepts an identifier (such as an ID), prepares a DELETE SQL query, binds parameters, executes the statement, and returns the number of affected rows or false on failure.

? CRUD Class with Delete Method

? View Code Example
// PHP CRUD class with a secure delete method
class User {
    private $conn;
    private $table = "users";

    public function __construct($db) {
        $this->conn = $db;
    }

    public function delete($id) {
        $stmt = $this->conn->prepare("DELETE FROM " . $this->table . " WHERE id=?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            return $stmt->affected_rows;
        }
        return false;
    }
}

? Using the Delete Method

? View Code Example
// Connecting to database and deleting a user record
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$user = new User($conn);
$rows_deleted = $user->delete(1);

if ($rows_deleted !== false) {
    echo "Number of rows deleted: " . $rows_deleted;
} else {
    echo "Deletion failed.";
}

$conn->close();

? Live Output / Explanation

If the record with the specified ID exists, the script outputs the number of rows deleted. If no record matches or execution fails, an error message is displayed.

? Use Cases

  • Admin panels for user management
  • Removing inactive or obsolete records
  • Account deletion features
  • Database cleanup operations

✅ Tips & Best Practices

  • Always validate IDs before deletion
  • Check affected rows to confirm success
  • Log deletions for audit tracking
  • Consider soft deletes when data recovery is required

? Try It Yourself

  • Extend delete to accept multiple IDs
  • Create a confirmation form before deletion
  • Implement a soft delete using a deleted flag
  • Store deletion timestamps for auditing