PHP & MySQL - Delete data from a database Tutorial

In this tutorial we learn how to delete records from a database table with PHP and an SQL query.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

For this tutorial, please start the MySQL module in your XAMPP control panel.

How to delete data from a table

We can delete data from our table with the DELETE FROM query. Typically, the DELETE FROM query includes the WHERE clause to delete only select records.

Syntax:
DELETE FROM table
WHERE column = value
Example: delete data
<?php

$serverName = "localhost";
$userName = "root";
$password = "";
$dbName = "trainingDB";

$conn = mysqli_connect($serverName, $userName, $password, $dbName);
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }

// delete record
$sql = "DELETE FROM Users WHERE userID=1";
mysqli_query($conn, $sql);

// show data
$sql = "SELECT userID, name, email FROM Users";
$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_assoc($result)){

    echo "User ID: " . $row['userID'] . "<br>" .
         "User Name: " . $row['name'] . "<br>" .
         "User Email: " . $row['email'] . "<br><br>";
 }


mysqli_close($conn);
?>

When we run the example above, it will delete John Doe from the table. When the users are printed to the page, we can see that John Doe is no longer among the entries.

Summary: Points to remember

  • We delete entries from our table with the DELETE FROM query in combination with the WHERE clause.
  • If we don’t specify the WHERE clause, all our entries will be deleted.