Reputation: 376
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
Upvotes: 0
Views: 52
Reputation: 212
If you want to do the query once you can make a request like this :
$values = implode(", ", $result);
$sql = "SELECT sub1, sub2 FROM students WHERE students.id IN (" . $values . ")";
This will return you all your students with one request
EDIT : removed the foreach, thanks Don't Panic
Upvotes: 1