我正在尝试创建一个动态 WHERE 子句,根据从下拉菜单中选择的选项,它将编译正确的 WHERE 子句。但我不认为我做得对。
首先应该有一个默认的 WHERE 子句,无论从下拉菜单中选择哪个选项,都应该有一个 WHERE 子句检查选中,SessionId
所以这应该是SessionId = ?
然后根据从下拉菜单中选择的选项,它将编译 WHERE 子句中的其他字段。有两个下拉菜单,分别是Students
和Questions
。可能的结果是:
Student selected != 'All'
: 添加StudentId
= ? 在 WHERE 子句中
Student selected == 'All'
:删除StudentId
= ?从 WHERE 子句
Question selected != 'All'
:添加QuestionId
= ?在 WHERE 子句中
Question selected == 'All'
:删除QuestionId
= ?从 WHERE 子句
我的问题是我该如何设置?
以下是我目前拥有的:
if(isset($_POST['answerSubmit'])) // we have subbmited the third form
{
$selectedstudentanswerqry = "
SELECT
StudentAlias, StudentForename, StudentSurname, q.SessionId, QuestionNo, QuestionContent, o.OptionType, q.NoofAnswers, GROUP_CONCAT( DISTINCT Answer
ORDER BY Answer SEPARATOR ',' ) AS Answer, r.ReplyType, QuestionMarks,
GROUP_CONCAT(DISTINCT StudentAnswer ORDER BY StudentAnswer SEPARATOR ',') AS StudentAnswer, ResponseTime, MouseClick, StudentMark
FROM Student s
INNER JOIN Student_Answer sa ON (s.StudentId = sa.StudentId)
INNER JOIN Student_Response sr ON (sa.StudentId = sr.StudentId)
INNER JOIN Question q ON (sa.QuestionId = q.QuestionId)
INNER JOIN Answer an ON q.QuestionId = an.QuestionId
LEFT JOIN Reply r ON q.ReplyId = r.ReplyId
LEFT JOIN Option_Table o ON q.OptionId = o.OptionId
";
if ($_POST['student'] != 'All'){
$selectedstudentanswerqry .= "
WHERE (SessionId = ? AND StudentId = ?)
";
}
if ($_POST['question'] != 'All'){
$selectedstudentanswerqry .= "
WHERE (SessionId = ? AND QuestionId = ?)
";
}
$selectedstudentanswerqry .= "
GROUP BY sa.StudentId, q.QuestionId
ORDER BY StudentAlias, q.SessionId, QuestionNo
";
global $mysqli;
$selectedstudentanswerstmt=$mysqli->prepare($selectedstudentanswerqry);
if ($_POST['student'] != 'All'){
// You only need to call bind_param once
$selectedstudentanswerstmt->bind_param("ii",$_POST["session"],$_POST["student"]);
}
if ($_POST['question'] != 'All'){
// You only need to call bind_param once
$selectedstudentanswerstmt->bind_param("ii",$_POST["session"],$_POST["question"]);
}
// get result and assign variables (prefix with db)
$selectedstudentanswerstmt->execute();
$selectedstudentanswerstmt->bind_result($detailsStudentAlias,$detailsStudentForename,$detailsStudentSurname,$detailsSessionId,$detailsQuestionNo,
$detailsQuestonContent,$detailsOptionType,$detailsNoofAnswers,$detailsAnswer,$detailsReplyType,$detailsQuestionMarks,$detailsStudentAnswer,$detailsResponseTime,
$detailsMouseClick,$detailsStudentMark);
$selectedstudentanswerstmt->store_result();
$selectedstudentanswernum = $selectedstudentanswerstmt->num_rows();
}
?>