简体   繁体   中英

Store several words in a session array and then show them

I'm writting a quiz. First the question is shown in question.php then in answer.php, the answer is analised, if the answer is right the word is stored in an array and if wrong in another. Then go back to question.php and so on. When there are no more questions, the result.php will show which words have been correct and which ones were wrong.

Please note that the session array needs to include a new word every time the answer.php is loaded.

EDIT: The problem is that the session array is only storing the first item

My code:

answer.php :

 <?php
 session_start();

 $question = $_GET['question'];
 $user_answer = $_GET['user_answer'];
 $right_answer = mysql_query("SELECT french FROM words where english='$question'");
 $fila = mysql_fetch_assoc($right_answer); 
 $fila_french = $fila['french'];

 if ( $user_answer == $fila_french ) { 
    echo "Right"; 
    $_SESSION['right_words'] = array();
    array_push($_SESSION['right_words'], $question);
     }

     else { echo "Wrong"; 
     $_SESSION['wrong_words'] = array();
    array_push($_SESSION['wrong_words'], $question);
     }
 echo "<a href='question.php' > Next </a>";
 ?>

result.php :

 <?php
 session_start();

 $right_answers = implode(',',$_SESSION['right_words']);
 $wrong_answers = implode(',',$_SESSION['wrong_words']);  

 echo "<h1> You finished the test </h1> 
 <p> You have these words right: $right_answers</p>
 <p> You have these words wrong: $wrong_answers</p>
 <a href='../exercises.php'> Go back to exercises </a>";
 ?>

Thanks for you help!

You don't say what the problem is but you will only get 1 item in each array as in your if/else blocks you are assigning a new empty array to your session variables. You should check if these variables are already defined before doing this:

if (!$_SESSION['right_words']) { $_SESSION['right_words'] = array(); }

And do the same for 'wrong_words'.

For your result.php file, to list all of the answers separated by a comma you can use implode :

$right_answers = implode(',',$_SESSION['right_words']);
$wrong_answers = implode(',',$_SESSION['wrong_words']);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM