hi actually iu'm fetching 5 question id from db and saved in an array.
now i'm fetching questions and their respective options from database.
so i'want to save the option in seesions or cookies when ever user selected.
this is my code for fetching questions & ANSWERS.

public function display( )
{
$myqid=array();
$i=0;
$query="SELECT * FROM test  ORDER BY RAND() limit 5  ";
$result=mysql_query($query)or die("cannot select DB");
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result))
  {
$myid[i]=$row[qid];
i++;
}
$_SEESION['qid']=$myid;

}

if(!isset($_SEESION['qid']))
{
$id=join("," qid);
$query="SELECT * FROM test  where qid="$id";
$result=mysql_query($query)or die("cannot select DB");
$num=mysql_numrows($result);
echo "<table>";
echo "<tr>"."<td style='overfolw-hidden;width:400px;'> Question: </td>";
echo "<td style='overfolw-hidden;width:40px;'> OPTION A </td>";
echo "<td style='overfolw-hidden;width:40px;'> OPTION B </td>";
echo "<td style='overfolw-hidden;width:40px;'> OPTION C </td>";
echo "<td style='overfolw-hidden;width:40px;'> OPTION D </td>";
echo "</tr>";
while($row = mysql_fetch_array($result))
  {
echo"<tr>";
echo "<td>" . $row['question'] . "</td>";
echo "<td>$row[a]<input type='radio' name='$row[qid]' value='$row[a]'> </td>";
echo "<td>$row[b]<input type='radio' name='$row[qid]' value='$row[b]'> </td>";
echo "<td>$row[c]<input type='radio' name='$row[qid]' value='$row[c]'> </td>";
echo "<td>$row[d]<input type='radio' name='$row[qid]' value='$row[d]'> </td>";
echo"</tr>";
}
echo"</table> <br/>";

it will displaying 5 questions along wtith their answers.now i want to save the selected option in sessions or cookies using php.can u please re-write or correct my code to save the options in sessions using php

Dani AI

Generated

Good direction from : fix the typos first and make sure each question’s radio buttons share the same name. A simple pattern that scales is to name inputs by question id and post them as an array, then persist answers in the session. Also, only randomize once per user: pick 5 qids, store them in the session, and keep showing those same 5 until the quiz is submitted.

Here is a lean workflow you can drop in. It keeps the selected value per question in the session, supports page refresh, and uses the PRG pattern to avoid double posts.

<?php
session_start(); // start before any output

// 1) On first load, choose questions once and remember them.
if (empty($_SESSION['qids'])) {
    // TODO: fetch 5 qids from DB, e.g. SELECT qid FROM test ORDER BY RAND() LIMIT 5
    $_SESSION['qids'] = [/* qid1, qid2, qid3, qid4, qid5 */];
}

// 2) Handle submit: store selected radios in the session.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $posted = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY) ?? [];
    $validQids = array_flip($_SESSION['qids']);
    // keep only answers for the 5 chosen questions
    $answers = array_intersect_key($posted, $validQids);

    $_SESSION['answers'] = $answers;              // persist
    // Optional: also persist in a cookie (client-side, size-limited)
    setcookie('answers', json_encode($answers), [
        'expires'  => time() + 3600,
        'path'     => '/',
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    header('Location: '.$_SERVER['REQUEST_URI']);
    exit;
}

// 3) When rendering, use name="answer[QID]" and value as option id.
foreach ($_SESSION['qids'] as $qid) {
    // TODO: fetch question text and its options for $qid
    foreach ($options as $optId => $optLabel) {
        $checked = (($_SESSION['answers'][$qid] ?? null) === (string)$optId) ? ' checked' : '';
        echo '<label><input type="radio" name="answer['.$qid.']" value="'.$optId.'"'.$checked.'> '.$optLabel.'</label>';
    }
}

Notes:

  • Start the session before any HTML so the cookie header can be sent. (php.net)
  • Migrate away from mysql_*; it was deprecated in PHP 5.5 and removed in PHP 7. Use mysqli or PDO with prepared statements. (php.net)

Recommended Answers

All 8 Replies

You have some errors in your code:
- missing $ character at variable names for $i, $qid
- if qid is not a variable but rather an associative index it should be always enclosed within quotes
- the name of the $_SESSION array is misspelled (it is not $_SEESION)

The code won't work until you fix those errors.

To make sure I understand your question correctly:

  • you display 5 random questions from a database + several optional answers for each question (like a quiz where you chose one or more answers for each question)
  • then you want to store the chosen answers in session

Please confirm that this is what you want. And post the structure of the test table.

Why do you want to store the checked answers in the session? Do you intend to use them on many pages? If you want to display the results there is usually no need to store the answers in session. If you want to keep the results for longer it might be better to store the answers in database.

<table>
<tr>
<td> question1 </td>
<td> option a </td>
<td> option b </td><td> option c </td><td> option d </td>
</tr>
<tr>
<td> question2 </td>
<td> option a </td>
<td> option b </td><td> option c </td><td> option d </td>
</tr>
<tr>
<td> question3 </td>
<td> option a </td>
<td> option b </td><td> option c </td><td> option d </td>
</tr>
<tr>
<td> question4 </td>
<td> option a </td>
<td> option b </td><td> option c </td><td> option d </td>
</tr>
<tr>
<td> question5 </td>
<td> option a </td>
<td> option b </td><td> option c </td><td> option d </td>
</tr></table>

all options should kept in radio buttons & the question should be in text box.
here the user can have chance to select a single optioin for single question.i want to save that answer in sessions.is it possible for storing the selected radiuo button value.if possible can u please help with that piece of code. all 5 tables wiulkl generate dynamically using while loop.these are fetching from mysql.

In order to help you please post the structure of the tables with questions and answers.

OK, I have prepared a conceptual answer to your question. I hope this is what you are after. See the comments in the code.

// if the form has been submitted, set the session
if(isset($_POST['submit'])) {

    // reset the previous values
    $_SESSION['quiz'] = array();

    // get rid of the submit element in the $_POST
    // so you are left with only radio buttons values
    unset($_POST['submit']);

    // assign the values of the radio buttons to the $_SESSION['quiz'] array
    $_SESSION['quiz'] = $_POST;
}

// connect to database (use your connection code)
require_once 'dbconnect.php';
$link = dbConnect();

// initialize an array for randomly selected question IDs
$qid_arr = array();

// select random question IDs
$qquery = "SELECT `qid`, `question` FROM `test` ORDER BY RAND() LIMIT 5";
$qresult = mysqli_query($link, $qquery) or die("cannot query DB");

// form
echo '<form method="post" action="#">';

// table
echo '<table border="0">';

// display randomly selected questions 
while($qrow = mysqli_fetch_assoc($qresult)) {

    // code for textbox containig question
    $tb = '<input type="text" value="' . $qrow['question'] . '" />';

    // select optional answers for this question from the database
    $aquery = "SELECT `option`, `answer` FROM opt_answers WHERE qid={$qrow['qid']}";
    $aresult = mysqli_query($link, $aquery) or die("cannot query DB");

    // start the html table row
    echo "<tr><td>$tb</td></tr>";

    // ad a question and optional answers
    while($arow = mysqli_fetch_assoc($aresult)) {

        // name atribute for checkbox
        $cb_name = 'question-' . $qrow['qid'];

        // code for radio button
        // checkbox group name is question-1 for 1st question etc
        // checkbox value equals the letter of the optional answer
        $cb = '<input type="radio" name="' . $cb_name . '" value="' . $arow['option'] . '" />';

        // display the row
        echo "<tr><td>{$cb} {$arow['option']}) {$arow['answer']}</td></tr>\n";
    }
}

echo '</table>';

// submit button
echo '<input type="submit" name="submit" value="Submit">';

echo '</form>';

// for testing purpose only
// display the value of $_SESSION
if(isset($_SESSION)) {

    echo '<p><pre>';
    echo '**************************************<br />';
    echo print_r($_SESSION, 1);
    echo '**************************************';
    echo '</pre></p>';    
}

The code above is just a concept. It could be optimized (e.g. using JOIN).

hi broj1 :-)
he was asked about the storing the values in sessions when the radio buttons was checked is it possible for that in php?

Well, that is what above vode doeas. See first 12 lines.

And there is a small glitch in the code. The database connection part of the code should be moved on top. Sorry about that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.