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.
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.
// 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;
}
}
// 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();
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.