How to Effectively Delete Records with \'WHERE... IN\' Clauses in PDO Queries?

Linda Hamilton
Release: 2024-10-30 03:03:02
Original
460 people have browsed it

How to Effectively Delete Records with

PDO Queries with "WHERE... IN" Clauses

When working with PHP's PDO for database access, constructing "WHERE... IN" queries can be challenging. In this case, the goal is to delete records from a table based on a list of IDs obtained from a form.

Original Query

<code class="php">$query = "DELETE from `foo` WHERE `id` IN (:idlist)";
$st = $db->prepare($query);
$st->execute(array(':idlist' => $idlist));</code>
Copy after login

Problem

This query only deletes the first ID in the list, discarding the remaining IDs due to the comma separator.

Solution Using Question Marks

Since prepared statements cannot mix values with control flow logic (the commas), it is necessary to use one placeholder per value in the list. This is achieved by creating a comma-separated string of question marks and binding the individual IDs to them.

<code class="php">$idlist = array('260','201','221','216','217','169','210','212','213');

$questionmarks = str_repeat("?,", count($idlist)-1) . "?";

$stmt = $dbh->prepare("DELETE FROM `foo` WHERE `id` IN ($questionmarks)");

foreach ($idlist as $id) {
    $stmt->bindParam($id);
}</code>
Copy after login

This approach requires looping through the list to bind each ID sequentially, ensuring that all records are deleted as intended.

The above is the detailed content of How to Effectively Delete Records with \'WHERE... IN\' Clauses in PDO Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!