What are common pitfalls when using PHP to delete database records and how can they be avoided?
One common pitfall when deleting database records in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To avoid this, always use prepared statements with parameterized queries to securely delete records from the database.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize user input
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("DELETE FROM mytable WHERE id = :id");
// Bind the parameter and execute the query
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();