我在下面有一个动态where子句的查询,但是我遇到了放置GROUP BY和ORDER BY子句的问题。我认为它根本没有被触发,因为准备声明超出了这些条款。但它不仅仅允许我将子句行放在准备语句之上,或者它给出了一个错误,在完全不同的行中陈述未定义的问题。我的问题是GROUP BY和ORDER BY CLAUSE应该在哪里正确放置?
CODE:
$selectedstudentanswerqry = "
SELECT
sa.StudentId, StudentAlias, StudentForename, StudentSurname, q.SessionId,
...
FROM Student st
...
";
// Initially empty
$where = array('q.SessionId = ?');
$parameters = array($_POST["session"]);
$parameterTypes = 'i';
//check if POST is empty
// Check whether a specific student was selected
$p_student = empty($_POST["student"])?0:$_POST["student"]; // Now if $_POST['student'] is either 0 or empty $p_student will be 0
echo $p_student;
switch($p_student){
case 0:
//dont' add where filters
break;
default:
$where[] = 'sa.StudentId = ?';
$parameters[] .= $_POST["student"];
$parameterTypes .= 'i';
}
// If we added to $where in any of the conditionals, we need a WHERE clause in
// our query
if(!empty($where)) {
$selectedstudentanswerqry .= ' WHERE ' . implode(' AND ', $where);
global $mysqli;
$selectedstudentanswerstmt=$mysqli->prepare($selectedstudentanswerqry);
// You only need to call bind_param once
if (count($where) == 1) {
$selectedstudentanswerstmt->bind_param($parameterTypes, $parameters[0]);
}
else if (count($where) == 2) {
$selectedstudentanswerstmt->bind_param($parameterTypes, $parameters[0], $parameters[1]);
}
}
$selectedstudentanswerqry .= "
GROUP BY sa.StudentId, q.QuestionId
ORDER BY StudentAlias, q.SessionId, QuestionNo
";
答案 0 :(得分:1)
在GROUP BY / ORDER BY子句下移动包含bind_param()的prepare语句和if语句。您在}
之上的收盘$selectedstudentanswerqry
可以上移到if (count($where) == 1)
以上