Delete data from MySQL using PHP

How to Delete Data from a MySQL Database Using PHP?

You can use the MySQL DELETE statement to remove existing records from a database table using PHP. The DELETE query allows you to permanently delete one or more records based on specified conditions. In PHP, you can execute a DELETE query using the MySQLi library and the mysqli_query() function. You can also use MySQLi prepared statements to delete records securely when values are received from HTML forms or user input.The syntax of delete query is mentioned below: Syntax


DELETE FROM table_name WHERE column_name=value;
The example of delete query is mentioned below: The following example delete some record in the "Employee" table: Code

<?php
  // Establish database connection
  $connection = mysqli_connect("localhost", "marcus", "xyz123", "my_database");

  // Check connection
  if (!$connection)
  {
    die("Could not connect with MySQL: " . mysqli_connect_error());
  }

  // Execute DELETE query
  $sql_query = 'DELETE FROM Employee WHERE FirstName = "Edge"';

  if (mysqli_query($connection, $sql_query))
  {
    echo mysqli_affected_rows($connection) . " record(s) deleted successfully.";
  }
  else
  {
    echo "Error occurred: " . mysqli_error($connection);
  }

  // Close database connection
  mysqli_close($connection);
?>

FAQ 1. How can I delete MySQL records securely using PHP? You should use MySQLi prepared statements to prevent SQL injection attacks when deleting records based on user input. 2. What is the difference between DELETE and TRUNCATE in MySQL? The DELETE statement removes records based on specified conditions, whereas TRUNCATE removes all records from a table. DELETE supports a WHERE clause, but TRUNCATE does not. 3. Does the DELETE statement permanently remove records from MySQL? The DELETE statement removes matching records from the table. Whether the deletion can be rolled back depends on the storage engine and whether the operation is performed inside an active transaction.