How to delete data in a database with PHP and MySQL
Deleting Data in a Database with PHP and MySQL
To delete data from a MySQL database using PHP, you can use the DELETE statement. The DELETE statement is used to remove rows from a table based on certain conditions.
Here is an example of how to delete data from a MySQL database using PHP:
// connect to the database $conn = mysqli_connect("localhost", "username", "password", "database_name"); // check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // prepare and execute the SQL query to delete the data $sql = "DELETE FROM users WHERE id = 1"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } // close connection mysqli_close($conn);
In this example, we connect to the MySQL database using the `mysqli_connect()` function. We then prepare and execute the SQL query using the `mysqli_query()` function. The query deletes the row with `id` equal to 1 from the `users` table. If the query is successful, we output a success message using `echo`. If there is an error, we output the error message using `mysqli_error()`. Finally, we close the database connection using `mysqli_close()`.
You can also use PHP variables to pass data dynamically in the DELETE statement. For example:
// connect to the database $conn = mysqli_connect("localhost", "username", "password", "database_name"); // check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // get id from URL parameter $id = $_GET['id']; // prepare and execute the SQL query to delete the data $sql = "DELETE FROM users WHERE id = $id"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } // close connection mysqli_close($conn);
In this example, we get the `id` value from a URL parameter using the `$_GET` superglobal variable. We then use the `$id` variable in the DELETE statement to delete a specific row from the `users` table.
For more information on how to delete data from a MySQL database using PHP, you can visit the following link: https://www.w3schools.com/php/php_mysql_delete.asp.
Written by: Maria Jensen 16-06-2023 Written in: PHP tutorials
This tutorial is exactly what I needed! 👍 The step-by-step instructions and code examples made it super easy to understand how to delete data in a database using PHP and MySQL . I’ve been struggling with this task for a while, but now I feel confident in my skills. Thank you so much for sharing this valuable information! 😊