I have a typical situation, where I need pull multiple rows from mysql by their ID’s. I only know two methods how to do so, but I’m wondering if there is a better way to do this? and if there isn’t, then which one of my own methods is most neatest/fastest/better?
My 1st method: (~0.0003030)
$ids = array(3, 4, 6, 11);
foreach ($ids as $id) {
$task = $DB->query_first("SELECT * FROM tasks WHERE `id` = '$id'");
DoSomethingWithTheTask($task);
}
My 2nd method: (~0.0001040)
$ids = array(3, 4, 6, 11);
foreach ($ids as $id) {
$wheres[] = '`id` = \'' . $id . '\'';
}
$tasks = $DB->query("SELECT * FROM tasks WHERE " . implode(' OR ', $wheres));
while ($task = $DB->fetch_array($tasks)) {
DoSomethingWithTheTask($task);
}
The reason why I’m even considering the second method, is because it uses only 1x query.. However, I strongly believe that both of these methods are not neat and need to be optimized. As far as I know, you cannot make a query like this: WHERE id = '2, 3, 4'.
Actually, you can. IN operator does that.
would do the trick. you can use both numeric or string values with IN operator
As Johan failed with example, here is a right way
for the frequent use I’d make a placeholder, to call the whole expression this way
to answer your questions from the comments, here is a code from my db class
getArr() method has no direct relation to this as it’s responsible for only type of result.