Values from a loop in one query
First of all, I'm using PDO. I believe it can be done using prepare
query, but I have no idea how.
The problem is, I got an array with values, and I need to check, if those values exist in the database.
Right now, it looks like:
foreach( $arr as $id ) {
$match =$PDO->query("SELECT `id` FROM `users` WHERE `id` = " . intval($id))->fetch();
if(isset($match['id']))
//exist
else
//not exist.
}
I don't wan't to run this query in every loop to check if the $id
exist in the database.
So is there any way, to collect all of those values from foreach, and then run a one query to check if each value exist in the data开发者_开发知识库base?
MySQL can handle lists of arguments:
SELECT field FROM table WHERE field IN (value1, value2, value3)
You can use PHP's join()
function to create a list of comma-seperated values from your array of ids and plug that into the SQL query. You can decide whether you want the database to count the number of result or just return all of them. In either case you will have only one database query in total.
How about this:
// Do query
$result = $PDO->query("SELECT `id` FROM `users` WHERE `id` IN (".implode(', ',$arr).")");
// Loop results (i.e. existing)
while ($row = $result->fetch()) {
// Do exist action here for $row['id']
unset($arr[array_search($row['id'],$arr)]);
}
// Loop remaining values in $arr (i.e. not existing)
foreach ($arr as $notexist) {
// Do not exist action here
}
精彩评论