PHP MySQL Delete


Deleting data from a database table

The SQL DELETE statement can be used to delete records from a table, just as it can be used to insert records into tables. It's usually combined with the WHERE clause to delete only the records that meet a set of parameters or conditions.


The following is the DELETE statement's basic syntax:


  DELETE FROM table_name WHERE column_name=some_value


Let's create a SQL query that uses the DELETE statement and the WHERE clause, and then run it through the PHP mysqli query() function to delete the tables' records.

The PHP code in the following example deletes the records of those people whose first name is John from the people table.


<?php
  /* Attempt MySQL server connection. Assuming you are running MySQL
  server with default setting (user 'root' with no password) */
  $mysqli = new mysqli("localhost", "root", "", "demo");

  // Check connection
  if($mysqli === false){
  die("ERROR: Could not connect. " . $mysqli->connect_error);
  }

  // Attempt delete query execution
  $sql = "DELETE FROM persons WHERE first_name='John'";
  if($mysqli->query($sql) === true){
  echo "Records were deleted successfully.";
  } else{
  echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
  }

  // Close connection
  $mysqli->close();
?>