What are some best practices for deleting items from a database using PHP?
When deleting items from a database using PHP, it is important to sanitize user input to prevent SQL injection attacks. It is also good practice to use prepared statements to securely interact with the database. Additionally, always remember to check for errors and handle them appropriately to ensure the deletion process goes smoothly.
<?php
// Establish a 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);
}
// Sanitize user input
$id = $_GET['id'];
$id = mysqli_real_escape_string($conn, $id);
// Prepare and execute the delete statement
$stmt = $conn->prepare("DELETE FROM table_name WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
// Check for errors
if ($stmt->error) {
echo "Error: " . $stmt->error;
} else {
echo "Record deleted successfully";
}
// Close the statement and connection
$stmt->close();
$conn->close();
?>
Related Questions
- Are there any best practices or guidelines to follow when creating short links in PHP?
- How can PHP developers ensure that only specific file formats are allowed for upload, such as jpg, gif, png, bmp, tga, and ico?
- What are the steps involved in using JavaScript/AJAX along with a PHP script to update specific parts of an HTML page without refreshing the entire page?