What are potential pitfalls when deleting data records in PHP using mysqli_query?
When deleting data records in PHP using mysqli_query, a potential pitfall is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with placeholders to securely pass user input to the query. Additionally, make sure to handle errors that may occur during the deletion process to provide proper feedback to the user.
// Example of securely deleting a data record using prepared statements
// Assuming $connection is a valid mysqli connection
$id = $_GET['id']; // Assuming user input for the record to delete
// Prepare the statement
$stmt = $connection->prepare("DELETE FROM table_name WHERE id = ?");
$stmt->bind_param("i", $id);
// Execute the statement
if ($stmt->execute()) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $connection->error;
}
// Close the statement and connection
$stmt->close();
$connection->close();
Related Questions
- Are there any best practices for setting expiration dates in headers using PHP?
- What are some best practices for checking if a variable has a value in PHP, especially when dealing with non-numeric values?
- What potential pitfalls should be considered when calculating dates based on user input in PHP?