← Back to Chapters

PHP MySQL CRUD – Delete Data

?️ PHP MySQL CRUD – Delete Data

? Quick Overview

The Delete operation in CRUD (Create, Read, Update, Delete) is used to permanently remove records from a MySQL database. In PHP, deletion is typically performed using the DELETE FROM SQL statement with MySQLi or PDO.

? Key Concepts

  • DELETE FROM removes rows from a table
  • WHERE clause targets specific records
  • Deletion is permanent unless backups or soft deletes exist

? Syntax / Theory

The basic SQL syntax used in PHP for deleting records:

DELETE FROM table_name WHERE condition;

? Code Example

? View Code Example
// PHP script to delete a record from MySQL using MySQLi
<?php
$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);
}

$sql = "DELETE FROM users WHERE id=1";

if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

? Live Output / Explanation

Expected Result

If the record with id = 1 exists, it will be removed from the users table and a success message will be displayed.

? Interactive Example

This JavaScript example simulates a delete confirmation before running a delete action.

? View Code Example
// Confirmation dialog before deleting a record
function confirmDelete() {
return confirm("Are you sure you want to delete this record?");
}

? Use Cases

  • Removing inactive or banned user accounts
  • Deleting outdated records from logs
  • Admin-controlled data cleanup

✅ Tips & Best Practices

  • Always use a WHERE clause to avoid deleting all records
  • Use prepared statements to prevent SQL injection
  • Consider soft deletes for recovery and audits

? Try It Yourself

  • Delete a user using an email instead of ID
  • Rewrite the delete query using PDO prepared statements
  • Implement a soft delete using a deleted column