1

我在下面有一个带有动态 where 子句的查询,但我对放置 GROUP BY 和 ORDER BY 子句的位置有疑问。我认为它根本没有被触发,因为准备语句在这些子句之前。但它并不仅仅允许我将子句行放在准备语句之上,或者它给我一个错误,在完全不同的行中说明未定义的问题。我的问题是 GROUP BY AND ORDER BY CLAUSE 应该正确放置在哪里?

代码:

$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
        ";
4

1 回答 1

1

将包含 bind_param() 的 prepare 语句和 if 语句移到 GROUP BY/ORDER BY 子句下方。}您在上方有一个关闭$selectedstudentanswerqry,可以向上移动到上方if (count($where) == 1)

于 2013-02-18T16:38:31.140 回答