vendredi 20 mars 2015

Checkbox error when false. [duplicate]


This question already has an answer here:




Im getting errors when my checkboxes remains unchecked. The error message is: Notice: Undefined index: answer_1 in C:\MAMP\htdocs\webutvikling\query.php on line 121


which is where the $value variable is:



for ($i=0; $i < $steg; $i++) {
$value = $_POST["answer_$i"];
echo " <input type='hidden' name='answer_$i' id='answer_$i' value='$value' />\n";
}


When the checkboxes is checked, there is no error at all. I have added some comments further down below that might help.



<?php
//Questionsarray

$questions = array(
array(
'text' => 'Hva heter du?',
'type' => 'text',
),
array(
'text' => 'Er du cool?',
'type' => 'checkbox',
),
array(
'text' => 'Hvor gammel er du?',
'type' => 'text',
),
array(
'text' => 'Er du awesome?',
'type' => 'checkbox',
),
array(
'text' => 'Bor du i Santa Monica?',
'type' => 'checkbox',
)
);

$steg = isset($_POST['step']) ? $_POST['step'] : 0;

$spm_teller = count($questions);

$submitted = isset($_POST['step']) ? true : false;



if ($submitted) {
if (isset($_POST ['next'])) {
$steg = $_POST['step'] + 1;
} else {
$steg = $_POST['step'] - 1;
}
}

echo "<p> <a href='{$_SERVER['PHP_SELF']}'> Start på nytt </a> </p> \n";

if ($steg >= $spm_teller ) {
echo "<p> Ferdig </p>";

//Giving values to the checkbox when checked/unchecked

foreach ($questions as $key => $questions) {
if ( $questions['type'] == 'checkbox' ) {
if (isset($_POST["answer_$key"])){
$_POST["answer_$key"] = "Ja!";
} else {
$_POST["answer_$key"] = "Nei!";
}
}
echo $questions['text'] . ': ' . $_POST["answer_$key"] . "<br>\n";

}


} else {
echo " <p> Du er nå på steg nr: $steg </p>";
echo " <form target='' method='post'>\n";
echo " <input type ='hidden' name='step' id='step' value='$steg' />\n";



//Echoing questions

echo $questions[$steg]['text'] . " <br />\n";
if (!empty($_POST["answer_$steg"])) {
$value = ($_POST["answer_$steg"]);
} else {
$value = '';
}

//Checking if the checkbox is true or false. Im thinking maybe the error is here? When I check the checkboxes I get no errors, but when it remains unchecked i get the error code: Notice: Undefined index: answer_1 in C:\MAMP\htdocs\webutvikling\query on line 121

if ($questions[$steg]['type'] == 'checkbox') {
if ($value == 'on' ) {
$selected = ' checked="checked"' ;
} if ($value == '') {
$selected = '';
}
echo "<input type = 'checkbox' name='answer_$steg' id='answer_$steg' $selected />\n";
} else {
echo "<input type = 'text' name='answer_$steg' id='answer_$steg' value='$value' />\n";
}

//Stores all the answers and puts it in the $value variable

for ($i=0; $i < $steg; $i++) {
$value = $_POST["answer_$i"];
echo " <input type='hidden' name='answer_$i' id='answer_$i' value='$value' />\n";
}

echo "</form> \n ";
}



?>
</body>
</html>

Aucun commentaire:

Enregistrer un commentaire