php - Save $_SESSION from a list of checkbox data? -
im trying save $_session data keep checked values on page refresh, have code written missing piece.
session code:
session_start(); if(isset($_post['submit'])) { //user posted variable $checks = $_post['personalization_result']; if(isset($_post['personalization_result'])) { $_session['value'] = $_post['personalization_result']; } else { $_session['value'] = ''; } }
form code:
<form action="" method="post" id="question-form"> <input type="hidden" name="submit" value="1"> <li> <input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_session['value']['memory_0'] ?>" value="0" /> <input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" /> </li> <li> <input name="personalization_result[memory_1]" type="hidden" class="<?php echo $_session['value']['memory_1'] ?>" value="0" /> <input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" /> </li> //there many checkboxes, 2 demo purposes <input class="submit" type="submit" value="send" /> </form>
for testing echoing $_session['value']['memory_0']
&& $_session['value']['memory_1']
inside hidden input, return properly, if input checked class 1, if it's unchecked class 0.
i not sure best way if = 1 echo checked="checked"
my shotty attempt:
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_session['value']['memory_0'] ?>" value="0" /> <input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php if($_session['value']['memory_0'] = 1) {echo 'checked="checked"';} ?> />
this returns error "cannot use scalar value array", , dont how thats written up.
so given information, whats best way write if value = 1 return checked="checked"
?
this make php cleaner , scalable:
use function @ top:
session_start(); function checkbox($id) { $ischecked = ''; if (isset($_session['value']['memory_'.$id])) { $ischecked = ($_session['value']["memory_".$id] == 1) ? 'checked="checked"' : ''; } echo '<input name="personalization_result[memory_'.$id.']" type="checkbox" '; echo 'value="1" id="personalization_result_memory_'.$id.'" '; echo $ischecked.' />'; }
and instead of writing out <input ... <?php ... ?> ... />
every single checkbox, use
<?php checkbox(0); ?> <?php checkbox(1); ?>
Comments
Post a Comment