"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle \"WHERE... IN\" Queries with PDO When Deleting Multiple Records?

How to Handle \"WHERE... IN\" Queries with PDO When Deleting Multiple Records?

Published on 2024-11-13
Browse:260

How to Handle \

Handling "WHERE... IN" Queries with PDO

When using PDO for database access, managing queries with "WHERE... IN" clauses can pose a challenge. Consider the following scenario: You need to remove entries from a database table based on a list of checked form items, represented as "$idlist" with variable length and content (e.g., '260,201,221,216,217,169,210,212,213').

Initially, using a query like the one below might seem logical:

$query = "DELETE from `foo` WHERE `id` IN (:idlist)";

However, this approach only deletes the first ID. The commas and subsequent IDs are mistakenly ignored.

To overcome this issue, it's crucial to understand the behavior of prepared statements in PDO. Values can be bound to placeholders using either numbered or named parameters. For a "WHERE... IN" query, each ID in the list should have its own placeholder.

The solution requires a dynamic approach:

$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)");

Next, bind each ID to a corresponding question mark:

for ($i = 0; $i bindParam($i   1, $idlist[$i]);
}

This method ensures that each item in the list is properly bound to a placeholder, allowing the query to successfully delete the intended records.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3