Jump to content

session variable values disappear with additional POST requests to same URL


dropkick_pdx

Recommended Posts

It's been a while since I've needed to whip anything substantial up from scratch, so my scripting is a little (lot) fast and loose (weird/inefficient) here. :)

 

I'm trying to mock up a script that's essentially a quiz/survey. There are a handful of topics, each with a few screens of yes/no questions. At the end, it returns a list of recommendations based on the answers gathered.

 

The script is posting back to itself. Using print_r ($_SESSION), it seems like all of the post values for the first screen of questions are being assigned to the session array as expected. When the second screen of questions is answered, their values are assigned as well, but the values for the first set go away completely. This continues through subsequent screens, with the values from the previous screen present and all others before missing.

 

I'd really appreciate a look at my code to see if you tell me the cause or error(s).

 

Thanks!

 

<?php
session_start;
include('_config.php');

// database connect
$dbc = mysqli_connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname);

// set to section 1, page 1 if no values are in _POST array
  if (($_SERVER['REQUEST_METHOD'] ==  'GET') || (!isset($_POST['section']))) {
  	$section	= 1;
  	$page 		= 1;
  }
  else {
// something was posted, so...set those values in session variable
foreach($_POST as $key => $data) { 
$_SESSION[$key] = $data; 
}
// debug: display contents of the session array
print_r ($_SESSION);

// which section and page?
  	$section	= (int) $_POST['section'];
  	$page 		= (int) $_POST['next'];
  }

// check if last topic
$query = "SELECT * FROM hw_topics";
$data = mysqli_query($dbc, $query);
  if ($section == mysqli_num_rows($data)) {
    $last_section = true; 
  }
  else {
    $last_section = false;
  }

// get current topic name and info
$query = "SELECT topic, display_name, pages_in_topic FROM hw_topics WHERE topic_id = '$section'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
  $row = mysqli_fetch_array($data);
  $topic_display_name = $row['display_name'];
  $pages_in_topic = $row['pages_in_topic'];
  }

// test if last page in topic	
$topic_pages = $row['pages_in_topic'];
if ($page == $topic_pages) {
    $last_page_in_section = true;
  }
  else {
    $last_page_in_section = false;
  }

// set form action (set to this script or to recommendations when last section is complete 
if (($last_section == true) && ($last_page_in_section == true)) {
    $form_action = $CFG->reccomend;
  }
  else {	
    $form_action = $_SERVER['PHP_SELF'];
  }

// get current page headline
$query = "SELECT page_headline FROM hw_pages WHERE topic_id = '$section' AND page_number = '$page'";
$data = mysqli_query($dbc, $query);

if (mysqli_num_rows($data) == 1) {
  // The headline row was found so display the headline
  $row = mysqli_fetch_array($data);
  $page_headline = '<h2>' . $row['page_headline'] . '</h2>';
  }


// Grab the question data from the database to generate the list and form fields
$query = "SELECT question_id, question_number, question_text FROM hw_questions WHERE topic_id = '$section' AND page_id = '$page' ORDER BY question_number";
$data = mysqli_query($dbc, $query);
$questions = array();
  while ($row = mysqli_fetch_array($data)) {
    array_push($questions, $row);
  }

include($CFG->includesdir.'/header.php');
?>
<div id="head">
	<h1>Assessment<?php if (isset($topic_display_name)) { echo ': <em>' . $topic_display_name  . '</em>'; } ?></h1>
	<p class="paging">Page <?php echo $page; ?> of <?php echo $pages_in_topic; ?></p>
</div><!-- #head -->
<div id="content">
<p class="instr">Please complete this survey. We'll generate a list of recommendations and resources for your organization.</p>

<div id="questions">
<?php echo $page_headline; ?>
<form method="post" action="<?php echo $form_action; ?>">

		<table border="0" cellpadding="0" cellspacing="0">
		<thead>
			<tr>
				<td></td>
				<td class="qtext"></td>
				<td class="qanswer">yes</td>
				<td class="qanswer">no</td>
				<td class="pad"></td>
			</tr>
		</thead>

<?php 
if ($questions) { 
    // display question rows
    foreach ($questions as $question) {
      echo '<tr>';
      echo '<td class="qnumber">' . $question['question_number'] . '.</td>';
      echo '<td class="qtext"><p>...' . $question['question_text'] . '</p></td>';
      echo '<td class="qanswer"><div class="radio" id="box-yes"><input type="radio" value="yes" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio" /></div></td>';
      echo '<td class="qanswer"><div class="radio" id="box-no"><input type="radio" value="no" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio"';
      $field_name = 'qid_' . $question['question_id'];
      if (isset($_SESSION[$field_name])) {
        echo ' checked="checked"';
      }
      echo ' /></div></td>';
      echo '<td class="pad"></td>';
      echo '</tr>';
    }
  }
  else {
    echo '<tr>';
    echo '<td colspan="3" class="qtext"><p>No questions found in the database for this page.</p></td>';
    echo '<td class="pad"></td>';
    echo '</tr>';
  }
?>
		</table>

	<ul id="controls">
<?php 
if ($last_page_in_section == true) 
  { 
  $section++; 
  $page = 1; 
  } 
  else {
  $page++;
  }
  echo '<input type="hidden" value="' . $section . '" name="section" />';
  echo '<input type="hidden" value="' . ($page) . '" name="next" />';
  if (($last_section == true) &&  ($last_page_in_section == true)) {
    echo '<li><input type="submit" value="Submit Answers and Get Recommendations" name="submit" id="submit" /></li>';
  }
  else {
    echo '<li><input type="submit" value="Next Page" name="submit" id="next" /></li>'; 
  }
?>
	</ul><!-- #controls -->
		</form>
</div><!-- #questions -->

<?php
mysqli_close($dbc);
include($CFG->includesdir.'/footer.php');
?>

Link to comment
Share on other sites

Many thanks for the reply.

 

I suspect you are 'overwriting' your session variable on each subsequent page

That seems sorta like what's going on, but I don't think it should actually be happening (that's the jist of my problem). I'm trying to understand how that would happen or what's causing it.

 

Clarification: I think I'm dropping each POST value into it's own session variable. (see snip below) My understanding is that unless another value is assigned to that variable during the session, it should still exist. Right? Each post operation seems to wipe out any session variables set on previous posts. I'm just not getting why.  :'(

 

foreach($_POST as $key => $data) { 
$_SESSION[$key] = $data; 
}

Link to comment
Share on other sites

At what level is your question_id unique? You are using it for the HTML field name and then assigning to the session. All of the questions would have to have an ID that is unique across ALL pages of the survey.

 

Try putting a print_r($_SESSION) and print_r($_POST) BEFORE you assign the post variables to the session and then print_r($_SESSION) AFTER the assignment. That might help explain what is happening. Also, take a look at the HTML for each page, specifically the name attribute of each form field.

 

By the way (not related to your question - I think) you may want to re-evaluate this code:

 

      echo '<td class="qanswer"><div class="radio" id="box-yes"><input type="radio" value="yes" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio" /></div></td>';
      echo '<td class="qanswer"><div class="radio" id="box-no"><input type="radio" value="no" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio"';
      $field_name = 'qid_' . $question['question_id'];
      if (isset($_SESSION[$field_name])) {
        echo ' checked="checked"';
      }
      echo ' /></div></td>';

It looks like you are assigning the CHECKED attribute to the NO radio if the field is set. Shouldn't that be assigned to the YES field?

 

Link to comment
Share on other sites

At what level is your question_id unique? You are using it for the HTML field name and then assigning to the session. All of the questions would have to have an ID that is unique across ALL pages of the survey.

I'm pulling in the primary key for each question when I pull it from the db. So, each field name & ID ends with the primary key (assuring a unique ID).

 

Try putting a print_r($_SESSION) and print_r($_POST) BEFORE you assign the post variables to the session and then print_r($_SESSION) AFTER the assignment.

Great simple debug step I hadn't looked at yet. I haven't examined the $_POST array at that stage. Good call.

 

By the way (not related to your question - I think) you may want to re-evaluate this code:

 

      echo '<td class="qanswer"><div class="radio" id="box-yes"><input type="radio" value="yes" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio" /></div></td>';
      echo '<td class="qanswer"><div class="radio" id="box-no"><input type="radio" value="no" name="qid_' . $question['question_id'] . '" id="qid_' . $question['question_id'] . '" class="radio"';
      $field_name = 'qid_' . $question['question_id'];
      if (isset($_SESSION[$field_name])) {
        echo ' checked="checked"';
      }
      echo ' /></div></td>';

It looks like you are assigning the CHECKED attribute to the NO radio if the field is set. Shouldn't that be assigned to the YES field?

 

:) I saw that a while after I posted the code. Was working on those switches when I realized my variable values were dying and got distracted.

 

I'll try the recommendations that have stacked up in this thread and post back if I identify the problem(s).

 

Thanks, all.

Link to comment
Share on other sites

It's always the stupidest oversights that make the most problems.

 

Right there on line 2...

session_start; should be session_start();

 

Printing the _SESSION and _POST arrays before and after I was reassigning the post variables to session variables helped me see that $_SESSION didn't exist before I assigned variables. Therefore, the session wasn't being created.

 

Thanks again, gang.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.