How can the PHP code be modified to ensure that the data is successfully deleted from the database when the ID is entered?
To ensure that the data is successfully deleted from the database when the ID is entered, the PHP code needs to include a DELETE query that targets the specific ID provided and executes it. This can be achieved by using a prepared statement to prevent SQL injection attacks and ensuring that the DELETE query is properly executed.
<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if ID is provided and execute DELETE query
if(isset($_GET['id'])) {
$id = $_GET['id'];
// Prepare and execute the DELETE query
$stmt = $conn->prepare("DELETE FROM table_name WHERE id = ?");
$stmt->bind_param("i", $id);
if($stmt->execute()) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
// Close connection
$conn->close();
?>