0

I have a while loop that displays 4 checkboxes from $choices with value answer_id from database.

<?php while($row=mysqli_fetch_assoc($choices)){ ?>
<input type="checkbox" name="choices[]" value="<?php echo $row['answer_id']; ?>"><?php echo $row['choice']; ?><?php } ?><?php } ?>
<input type="submit" name="submit" value="submit">

I want to send this array of selected choices to another page and store each of its value in different variables.

if(isset($choices)){
    $choice1id = $_POST['choices']; 
}


if(isset($choices)){
    $choice2id = $_POST['choices']; 
}


if(isset($choices)){
    $choice3id = $_POST['choices']; 
}


if(isset($choices)){
    $choice4id = $_POST['choices']; 
}

If user has selected 2 checkboxes so its value gets on index 0 and 1 in array and these 2 values get stored in variables choice1id and choice2id on another PHP page. But it says Warning: Undefined variable $choice1id, $choice2id etc. how do I solve this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
becky
  • 7
  • 4

1 Answers1

-1

I'm not sure if this is what you wanted. Seems like you want to get $_POST['choices'] and create variables from it? If so, first check if it was posted, then loop through each one. You can create dynamic variables in the loop. This will give you variables like $choice1id $choice2id .. etc

if(isset($_POST['choices'])){
  $ctr = 1;
  foreach ($_POST['choices'] as $choice) {
    $var = "choice" . $ctr . "id";
    $$var = $choice; 
    $ctr++;
  }
}
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • here it creates a trouble, if user selects only 2 checkboxes, it says choice3id and choice4id are undefined. How do i create variables at run time only for those checkboxes that are selected. – becky Jun 11 '21 at 08:29