2013-02-18 49 views
1

我有一个查询下面有一个动态where子句,但我遇到了放置GROUP BY和ORDER BY子句的问题。我不认为这是因为准备声明超出了这些条款而被触发。但它不仅仅允许我将子句行放在准备语句之上,或者它给了我一个错误,在完全不同的行中陈述未定义的问题。我的问题是GROUP BY和ORDER BY CLAUSE应该放在哪里?GROUP BY和ORDER BY子句在准备声明之后(mysqli)

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

回答

1

移动准备语句,并且如果含有bind_param()的GROUP BY/ORDER BY子句下方语句。你有一个关闭}刚好在$selectedstudentanswerqry以上,可以移动到if (count($where) == 1)以上