Deleting Data from Tables

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

Delete Records Conditions

Syntax

DELETE FROM table_name WHERE condition;

Example

<?php

    // Create connection
     $link = mysqli_connect("localhost", "root", "password", "demo");
    // Check connection
    if (!$link) {
      die("Connection failed: " . mysqli_connect_error());
    }

    // sql to delete a record
    $sql = "DELETE FROM user WHERE id=3";

    if (mysqli_query($link, $sql)) {
      echo "Record deleted successfully";
    } else {
      echo "Error deleting record: " . mysqli_error($link);
    }

?>

Delete All Data

Similar as mentioned above if you do not specify the WHERE clause in the DELETE statement all the rows from the table will be deleted. MySQL However, the target table itself won't be deleted that means the table structure, attributes, and indexes will remain intact.

The following statement will remove all the records from the user table:

Syntax

DELETE FROM table_name;

Example

<?php

    // Create connection
     $link = mysqli_connect("localhost", "root", "password", "demo");
    // Check connection
    if (!$link) {
      die("Connection failed: " . mysqli_connect_error());
    }

    // sql to delete a record
    $sql = "DELETE FROM user";

    if (mysqli_query($link, $sql)) {
      echo "Record deleted successfully";
    } else {
      echo "Error deleting record: " . mysqli_error($link);
    }

?>