PHP MySQL DELETE Query

DELETE statement is used to delete the records from a MySQL database table.

Deleting Database Table Data

Just as you insert records into tables, you can delete records from a table using the DELETE statement. It is typically used in conjugation with the WHERE clause to delete only those records that matches specific criteria or condition.

The basic syntax of the DELETE statement can be given with:

DELETE FROM table_name WHERE column_name=some_value

Let's make a SQL query using the DELETE statement and WHERE clause, after that we will execute this SQL query through passing it to the mysqli_query() function to delete the tables records. Consider the following "persons" table inside the "demo" database:

+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address        |
+-----------+------------+-----------+----------------------+
|         1 | Peter      | Parker    | peterparker@mail.com |
|         2 | John       | Rambo     | johnrambo@mail.com   |
|         3 | Clark      | Kent      | clarkkent@mail.com   |
|         4 | John       | Carter    | johncarter@mail.com  |
|         5 | Harry      | Potter    | harrypotter@mail.com |
+-----------+------------+-----------+----------------------+

The PHP code in the following example deletes all the records of persons from the above persons table whose first_name='John'.

Example

Download
  • <?php
  • /* Attempt MySQL server connection. Assuming you are running MySQL
  • server with default setting (user 'root' with no password) */
  • $link = mysqli_connect("localhost", "root", "", "demo");
  •  
  • // Check connection
  • if($link === false){
  •     die("ERROR: Could not connect. " . mysqli_connect_error());
  • }
  •  
  • // Attempt delete query execution
  • $sql = "DELETE FROM persons WHERE first_name='John'";
  • if(mysqli_query($link, $sql)){
  •     echo "Records were deleted successfully.";
  • } else{
  •     echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  • }
  •  
  • // Close connection
  • mysqli_close($link);
  • ?>

After the deletion the persons table will look something like this:

+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address        |
+-----------+------------+-----------+----------------------+
|         1 | Peter      | Parker    | peterparker@mail.com |
|         3 | Clark      | Kent      | clarkkent@mail.com   |
|         5 | Harry      | Potter    | harrypotter@mail.com |
+-----------+------------+-----------+----------------------+

As you can see the records has been deleted successfully from the persons table.

 

Warning:The WHERE clause in the DELETE statement specifies which record or records should be deleted. If you omit the WHERE clause, all records will be deleted.

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.