What is the correct syntax for deleting data from a MySQL database using PHP?
When deleting data from a MySQL database using PHP, you need to establish a connection to the database, construct a SQL DELETE query, and then execute the query using a function like mysqli_query(). Make sure to properly sanitize user input to prevent SQL injection attacks.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Construct the SQL DELETE query
$sql = "DELETE FROM table_name WHERE condition";
// Execute the query
if (mysqli_query($connection, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($connection);
}
// Close the connection
mysqli_close($connection);
?>
Related Questions
- What are some best practices for handling directory recognition in PHP scripts?
- How can the process of validating passwords in PHP be streamlined to account for special characters, umlauts, and other non-alphanumeric characters while maintaining security standards?
- How can patterns be adjusted when using preg_match in PHP to avoid errors related to unknown modifiers?