Question

I have a HTML page with multiple choice questions and a submit button. The Submit button leads to a .php page which includes code to 1) connect to phpmyadmin the sql database and the relevant table and, 2) the code below which tells/reminds the user what question number it was, the actual question, the correct answer (from the database) and their submitted answer.

My problem is that I want a score to be calculated and communicated to the user and it is not quite working. An error message tells me that the following line is not working

$answered = $row['select'.$_GET['a'.$x]] ;

I took this from another question/answer forum and I'm not quite sure what it fully states but it seems to be causing the error

Database is simple; Questionid, Questiontext and Correctanswer columns only.

The browser displays the following:

Question Number: 1
Question: ________ hablo
Correct Answer: Yo
Your Answer: Yo 

Notice: Undefined index: a2 in C:\xampp\htdocs\SSF\1B results.php on line 33

Notice: Undefined index: select in C:\xampp\htdocs\SSF\1B results.php on line 33 You answered 0 out of 1 questions correctly!

The code

$result = mysql_query("SELECT * FROM 1b")
              or die ('Connection to table failed');

$x = 0;
$score = 0;
while ($row = mysql_fetch_assoc($result)){

    echo "Question Number: " . $row['Questionid'] . '<br />';
    echo "Question: " . $row['Questiontext'] . '<br />';
    echo "Correct Answer: " . $row['Correctanswer'] . '<br />';
    foreach ($_GET['select'] as $value)
    echo "Your Answer: " . $value."\n" . '<br />';

    $answered = $row['select'.$_GET['a'.$x]] ;
    $correct = $row['Correctanswer'] ;

    if ($answered == $correct ) {
        $score++;
        $acolor = 'green' ;
    }
    else {
        $acolor = 'red' ;
    }

    $x = $x + 1;
}
echo 'You answered ' . $score . ' out of ' . $x . ' questions correctly!';
?>
Was it helpful?

Solution

$answered = $row['select'.$_GET['a'.$x]] ;

But when you echo 'Your answer', you use $value. Wouldn't this work?

 $answered = $value ;

(it would be helpful to see the form you are submitting though...)

OTHER TIPS

An undefined index error is what you get when you reference a value in an array by a key, but that key doesn't exist. For example:

$array = array(
        'abc'   =>  1,
        'def'   =>  2,
);

If I now try to reference some random key like $array['z'] I will get the error you mentioned.

The first error you get is telling you that your GET parameters don't even have the 'a2' key set. The second error you are getting because the 'select' key doesn't exist in your $row array.

We would need to see the form you are submitting to get a proper idea of what exactly is wrong though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top