I’m trying to write the code for an online form:
On page 1 there are just some demographic questions. It’s on that first page I start a session. When they submit their answers they get redirected to page 2 where I place some statements on which they can select their level of agreement.
- In case they want to go back their answers on the previous page are remembered thanks to the session.
- Ultimatly their answers will be transferred to a database (haven’t written that yet).
Problem:
-
I tried to multiply the amount of questions to 3 questions on page 2 but when I go to page 3 and return to page 2 the answers aren’t remembered?
-
If I only check some of the questions (not all of them) I get ‘Notice: Undefined index:’ with the line the unanswered question is on. Can this be solved somehow?
This is the code from page 2:
<form action="page3.php" method="post">
<?php
$options = array(
'Good' => 'Good',
'Neutral' => 'Neutral',
'Bad' => 'Bad',
);
checkbox( 'Question_1', 'Question_1', 'How good is your health?', $options );
checkbox( 'Question_2', 'Question_2', 'How good is your math?', $options );
checkbox( 'Question_3', 'Question_3', 'How good is your knowledge of astrofysics?', $options );
?>
<?php submit('Go To Step 3 »'); ?>
</form>
This is the code from page 3 (where the info from page 2 is stored in the SESSION variables):
<?php
include_once('header.php');
// Store data from page 1 in session
if ( ! empty( $_POST ) ) {
$_SESSION['Question_1'] = $_POST['Question_1'];
$_SESSION['Question_2'] = $_POST['Question_2'];
$_SESSION['Question_3'] = $_POST['Question_3'];
}
?>
And this is the code of the used function (from functions.php):
function checkbox( $name, $id, $label, $options = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ( $options as $value => $title ) : ?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="checkbox" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION['Question_1'],$_SESSION['Question_2'],$_SESSION['Question_3']) ? checked="checked":; ?>>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
What am I doing wrong?