PHP MySQL Delete Data

In PHP and MySQL, deleting data from a database table is a common operation. Here’s how you can delete data from a MySQL database using PHP.

Assuming we have a table called “users” with the following fields:

  • id (integer)
  • name (string)
  • email (string)
  • age (integer)

To delete data from the table, we use the SQL DELETE statement.

Here’s an example of deleting a user with a specific id:

<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'mydb');
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
// SQL query to delete a user by id
$sql = "DELETE FROM users WHERE id = 1";
if (mysqli_query($conn, $sql)) {
  echo "User deleted successfully";
} else {
  echo "Error deleting user: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

In the example above, we first connect to the database using mysqli_connect(). We then define the SQL statement to delete the user with id=1, using the DELETE statement and the WHERE clause. We execute the SQL statement using mysqli_query(), and check if it was successful. If there was an error, we print an error message using mysqli_error(). Finally, we close the database connection using mysqli_close().

You can modify the SQL query and the WHERE clause to delete data based on different criteria. For example, to delete all users with age greater than 30, you can use the following SQL query:

DELETE FROM users WHERE age > 30

And the PHP code to execute this query would look like this:

<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'mydb');
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
// SQL query to delete users with age greater than 30
$sql = "DELETE FROM users WHERE age > 30";
if (mysqli_query($conn, $sql)) {
  echo "Users deleted successfully";
} else {
  echo "Error deleting users: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>