我在下面的变量
中以数组形式返回了有限数量的学生(10)$ result变量是一个数组,它包含学生ID,如下例所示
Array (
[student1] => 4
[student2] => 1
[student3] => 3
[student4] => 2
[student5] => 5
[student6] => 10
[student7] => 12
[student8] => 16
[student9] => 17
[student10] => 18
)
我尝试了什么
$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) {}
我确定如何在一个中优化我的查询而不是循环10个查询
答案 0 :(得分:1)
如果您想提出这样的请求,请执行查询:
$values = implode(", ", $result);
$sql = "SELECT sub1, sub2 FROM students WHERE students.id IN (" . $values . ")";
这将通过一个请求返回所有学生
编辑:删除了foreach,感谢Don's panic