Skip to content
PHP Logo

How can a WHERE id IN(..) condition be used in SQL to delete multiple IDs in PHP?

To delete multiple IDs in PHP using a WHERE id IN(..) condition in SQL, you can construct a comma-separated list of IDs and pass it as a parameter in the SQL query. This allows you to delete multiple rows with a single query, improving efficiency and performance.

php
<?php
// Assuming $ids is an array of IDs to be deleted
$ids = [1, 2, 3, 4];

// Construct a comma-separated list of IDs
$idList = implode(',', $ids);

// Prepare the SQL query with the WHERE id IN(..) condition
$sql = "DELETE FROM table_name WHERE id IN ($idList)";

// Execute the query
$result = mysqli_query($connection, $sql);

if($result) {
    echo "Records deleted successfully.";
} else {
    echo "Error deleting records: " . mysqli_error($connection);
}

// Close the connection
mysqli_close($connection);
?>