I have a limited number of students (10) returned in an array in the below variable,
$result variable is a array, it contains student ID's like the example below
Array (
[student1] => 4
[student2] => 1
[student3] => 3
[student4] => 2
[student5] => 5
[student6] => 10
[student7] => 12
[student8] => 16
[student9] => 17
[student10] => 18
)
what i tried
$values = implode(", ", $result);
$sql = "SELECT sub1, sub2 FROM students WHERE students.id IN (" . $values . ")";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$subject = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if(empty($subject)) {
$response->getBody()->write
('{"error":{"message":"Invalid Request}}');
} else {
$subject = json_decode(json_encode($subject), True);
if (in_array("BIO", $subject))
{
return true;
}
else
{
return false;
}
print_r($subject);
}
} catch(PDOException $e) {}
I am sure How i can be optimize my query in one instead of looping 10 queries
IN()clause, it's much more efficient than running a single query inside your loop.