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
- How can PHP handle creating multiple files within a ZIP archive?
- What are the common challenges faced when dynamically filtering out elements, such as IMG tags, from Xpath queries in PHP?
- In what ways can PHP be optimized to handle the sorting and ranking of teams in a sports league based on various criteria like points and goal differences efficiently?