📜  PHP mysql-delete(1)

📅  最后修改于: 2023-12-03 14:45:12.274000             🧑  作者: Mango

PHP MySQL Delete

In PHP, you can delete data from a MySQL database using the DELETE statement. The DELETE statement is used to remove one or more rows from a table based on specified conditions.

Prerequisites

Before you can delete data from a MySQL database using PHP, make sure you have the following:

  • PHP installed on your system
  • A MySQL database set up and running
  • PHP MySQL extension enabled (most PHP installations come with it preinstalled)
Connecting to the MySQL Database

To delete data from a MySQL database, you first need to establish a connection. You can use the mysqli or PDO extension in PHP. Here, we will use the mysqli extension for demonstration.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Replace your_username, your_password, and your_database with your actual MySQL credentials.

Deleting Data

Once the connection to the MySQL database is established, you can execute the DELETE statement to delete data.

<?php
$sql = "DELETE FROM your_table WHERE condition";

if ($conn->query($sql) === true) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

Replace your_table with the name of the table from which you want to delete data. Modify condition to specify the criteria for deleting records. For example, if you want to delete a record with a specific id, the condition might be id = 1.

The code first prepares the DELETE SQL statement and then executes it using the query() method. If the query is executed successfully, it displays a success message. Otherwise, it displays an error message.

Remember to close the database connection using $conn->close() to release resources after you have finished deleting data.

Conclusion

In this guide, you have learned how to delete data from a MySQL database using PHP. Make sure to choose the right conditions when deleting records to avoid unintentional deletion of data.