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:
<code class="php">$query = "DELETE from `foo` WHERE `id` IN (:idlist)";</code>
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:
<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)");</code>
Next, bind each ID to a corresponding question mark:
<code class="php">for ($i = 0; $i < count($idlist); $i++) { $stmt->bindParam($i + 1, $idlist[$i]); }</code>
This method ensures that each item in the list is properly bound to a placeholder, allowing the query to successfully delete the intended records.
The above is the detailed content of How to Handle \'WHERE... IN\' Queries with PDO When Deleting Multiple Records?. For more information, please follow other related articles on the PHP Chinese website!