Skip to content
PHP Logo

How can you avoid SQL syntax errors when deleting data in PHP?

To avoid SQL syntax errors when deleting data in PHP, you should use prepared statements with placeholders for the values to be deleted. This helps prevent SQL injection attacks and ensures that the SQL syntax is correct.

php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL statement with placeholders
$stmt = $pdo->prepare("DELETE FROM mytable WHERE id = :id");

// Bind the parameter value to the placeholder
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

// Execute the statement
$stmt->execute();