Its outputs details incorrectly in php/html

不想你离开。 提交于 2020-01-14 12:10:10

问题


I want to display all the questions from the drop down menu when the user selects All from the question drop down menu and output it underneath. Problem is that it is not doing this and to make it worse, it is giving me undefined offset errors stating:

Notice: Undefined offset: ... in .... on line 605

Line 605 is:

echo '<p><strong>Question:</strong> ' .htmlspecialchars($arrQuestionNo[$key]). ': ' .htmlspecialchars($arrQuestionContent[$key]). '</p>' . PHP_EOL;

My question is how to fix the error and display all the questions if user selects All option?

I have a demo you can go through: DEMO

Follow steps below:

  • In Module drop down menu, select System Stratergy and submit
  • When Assessment drop down menu appears, select POKUB1 and submit
  • You will see students and question drop down menu. You can see that if you open up the drop down menus that there are 3 students and 2 questions. Please select a single student and All questions and ubmit. This is where you will see the errors when really I want to display all of the question's details here.

CODE:

Question Drop down menu:

<select name="question" id="questionsDrop">
<option value="0">All</option>
<option value=23">1</option>
<option value=32">1</option>
</select>

Below is code which determines display depending on which options are selected from question drop down menu.

    function StudentAnswers()
        {

        $selectedstudentanswerqry = "
            SELECT
            sa.StudentId, 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 st
            INNER JOIN Student_Answer sa ON (st.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
            ";

            // Initially empty
            $where = array('q.SessionId = ?');
            $parameters = array($_POST["session"]);
            $parameterTypes = 'i';


            // Check whether a specific question was selected
            $p_question = empty($_POST["question"])?'':$_POST["question"];

            switch($p_question){
            case 0:
                //dont' add where filters
                break;
            default:
                $where[] = 'q.QuestionId = ?';
                $parameters[] .= $_POST["question"];
                $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
            ";

        // get result and assign variables (prefix with db)
        $selectedstudentanswerstmt->execute(); 
        $selectedstudentanswerstmt->bind_result($detailsStudentId,$detailsStudentAlias,$detailsStudentForename,$detailsStudentSurname,$detailsSessionId,$detailsQuestionNo, 
        $detailsQuestionContent,$detailsOptionType,$detailsNoofAnswers,$detailsAnswer,$detailsReplyType,$detailsQuestionMarks,$detailsStudentAnswer,$detailsResponseTime,
        $detailsMouseClick,$detailsStudentMark);    

        $selectedstudentanswerstmt->store_result();
        $selectedstudentanswernum = $selectedstudentanswerstmt->num_rows(); 


            $question = array();

            while ($selectedstudentanswerstmt->fetch()) {

            $arrQuestionNo = array();
            $arrQuestionContent = array();



            $arrQuestionNo[ $detailsStudentId ] = $detailsQuestionNo;
            $arrQuestionContent[ $detailsStudentId ] = $detailsQuestionContent;



            $questions[] = $arrQuestionNo;
            $questions[] = $arrQuestionContent;

        }

        $selectedstudentanswerstmt->close();

        ?>

...........................................................................................

    <h2>STUDENT'S ANSWERS</h2>

    <?php   

              foreach ($questions as $key=>$question) {

    echo '<p><strong>Question:</strong> ' .htmlspecialchars($arrQuestionNo[$key]). ': ' .htmlspecialchars($arrQuestionContent[$key]). '</p>' . PHP_EOL;

    }
    }
    ?>

UPDATE:

Student Table structure:

CREATE TABLE `Student` (
 `StudentId` int(10) NOT NULL AUTO_INCREMENT,
 `StudentForename` varchar(25) NOT NULL,
 `StudentSurname` varchar(25) NOT NULL,
 `StudentAlias` varchar(15) NOT NULL,
 `StudentEmail` varchar(50) NOT NULL,
 `StudentUsername` varchar(20) NOT NULL,
 `StudentPassword` varchar(50) NOT NULL,
 `StudentDOB` date NOT NULL,
 `Year` int(2) NOT NULL,
 `CourseId` int(6) NOT NULL,
 `Active` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`StudentId`),
 KEY `FK_Course` (`CourseId`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8

Question Table Structure:

CREATE TABLE `Question` (
 `QuestionId` int(10) NOT NULL AUTO_INCREMENT,
 `SessionId` int(10) NOT NULL,
 `QuestionNo` int(3) NOT NULL,
 `QuestionContent` varchar(5000) NOT NULL,
 `NoofAnswers` int(2) NOT NULL,
 `ReplyId` int(1) NOT NULL,
 `QuestionMarks` int(4) NOT NULL,
 `OptionId` int(2) NOT NULL,
 PRIMARY KEY (`QuestionId`)
) ENGINE=InnoDB AUTO_INCREMENT=357 DEFAULT CHARSET=utf8

回答1:


Give this a try.......

$question = array();

while ($selectedstudentanswerstmt->fetch()) {
    // assuming you don't need the StudentId
    $questions[] = array('no' => $detailsQuestionNo,
                         'content' => $detailsQuestionContent);
}

and

foreach ($questions as $key => $question) {
    echo '<p><strong>Question:</strong> ' . 
         htmlspecialchars($question['no']) .
         ': ' . 
         htmlspecialchars($question['content']) . 
         '</p>' . 
         PHP_EOL;
}

EDITED

Or you can try this if your grouping by question:

$question = array();

while ($selectedstudentanswerstmt->fetch()) {
    if (true === isset($questions[$detailsQuestionId])) {
        $questions[$detailsQuestionId]['students'][] = $detailsStudentId;
    } else {
        $questions[$detailsQuestionId] = array();
        $questions[$detailsQuestionId]['no'] = $arrQuestionNo;
        $questions[$detailsQuestionId]['content'] = $arrQuestionContent;
        $questions[$detailsQuestionId]['students'] = array();
        $questions[$detailsQuestionId]['students'][] = $detailsStudentId;
    }
}

foreach ($questions as $questionId => $question) {
    // $question['no']
    // $question['content']

    foreach($question['students'] AS $key => $studentId) {
        // $studentId
    }
}

Or if your grouping by userID...

$students = array();

while ($selectedstudentanswerstmt->fetch()) {
    if (false === isset($students[$detailsStudentId])) {
        $students[$detailsStudentId] = array();
    }
    $students[$detailsStudentId][$detailsQuestionId] = 
                                       array('no' => $arrQuestionNo,
                                             'content' => $arrQuestionContent;
}

foreach ($students AS $studentId => $questions) {
    // $studentId
    foreach ($questions AS $questionId => $question) {
        // $questionId
        // $question['no']
        // $question['content']
    }
}



回答2:


Your foreach loop is iterating over the questions array, which was filled in with:

        $questions[] = $arrQuestionNo;
        $questions[] = $arrQuestionContent;

This means it's an indexed array, not an associative array; the keys are 0 and 1.

But then you echo $arrQuestionNo[$key] and $arrQuestionContent[$key]. These are associative arrays, whose keys are student IDs, not indexes starting from 0 (unless you happen to have students with these ID numbers).

Also, you initialize $arrQuestionNo and $arrQuestionContent to an empty array each time through the fetch loop. So when you're echoing the results at the end, these just contain the questions from the last row that was fetched.

You should use a multidimensional array:

while ($selectedstudentanswerstmt->fetch()) {
  $questions[$detailsStudentId][$detailsQuestionNo] = $arrQuestionContent;
}

Then your printing loop should be:

foreach ($questions as $studentId => $studentQuestions) {
  echo '<h2>Student '.htmlspecialchars($studentId).' Answers</h2>'. PHP_EOL;
  foreach ($studentQuestion as $questionNo => $content) {
    echo '<p><strong>Question:</strong> ' .htmlspecialchars($questionNo). ': ' .htmlspecialchars($content). '</p>' . PHP_EOL;
  }
}


来源:https://stackoverflow.com/questions/14382607/its-outputs-details-incorrectly-in-php-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!