0

I am facing a problem while storing variable data in array and then array to session. Only for one time the value is stored in array at 0 index, but when the next page loads on next button click to load the next test the value of array is overwritten.

<?php session_start();
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers[] = array('correct' => $correct);
$_SESSION["results"] = $answers;
print_r($_SESSION["results"]); ?>
2
  • 2
    Append to array with [] notation Commented Apr 14, 2016 at 14:36
  • @SaurabhSinha He has. Commented Apr 14, 2016 at 14:40

3 Answers 3

2

Just get answers before set :)

<?php session_start();
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers = (array_key_exists("results", $_SESSION)) ? $_SESSION["results"] : array();
$answers[] = array('correct' => $correct);
$_SESSION["results"] = $answers;
print_r($_SESSION["results"]);
?>
Sign up to request clarification or add additional context in comments.

Comments

0

If it is submitted then value shows

<?php session_start();
if(isset($_POST['submit']))
{
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers[] = array('correct' => $correct);
$_SESSION["results"] = $answers;
}
print_r($_SESSION["results"]); ?>

1 Comment

did you get your answer?
0

1.You don't need the "[ ]" while declaring an array.

2.The data gets overridden because you didn't check whether the data was set in the first place.

<?php 
ini_set('session.cookie_domain',"localhost");
session_start();
if(isset($_POST['submit']))
{
    $cat_name = $_POST["cat_name"];
    $which_test_id = $_POST["which_test_id"];
    echo $correct = $_POST["correct"];
    $answers = array('correct' => $correct);
    if(!isset($_SESSION["results"]))
    {
        $_SESSION["results"] = $answers;
    }
}
print_r($_SESSION["results"]); ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.