How can the PHP script be modified to successfully delete a selected row from a database table based on the ID passed through a link?
The PHP script needs to retrieve the ID passed through the link, sanitize it to prevent SQL injection, and then use a DELETE query to remove the corresponding row from the database table. This can be achieved by modifying the existing script to include these steps.
<?php
// Connect to the database
$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);
}
// Retrieve and sanitize the ID passed through the link
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// Delete the selected row from the database table
$sql = "DELETE FROM table_name WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Keywords
Related Questions
- How can the PHP script be optimized to improve performance and prevent potential vulnerabilities, such as directory traversal attacks?
- What are some common issues when using PHP to retrieve data from Yahoo Finance, such as empty data or timeouts?
- How can issues with missing features like avatar images and team lists be addressed when updating a website with PHP Fusion scripts?