0

I have a list which I am populating from my DB into multiple checkboxes using a foreach loop:

<?php 
$sections_arr = listAllForumBoards(0, 1, 100);
$count_board = count($sections_arr);
$ticker = 0;
foreach($sections_arr as $key => $printAllSections){
$ticker = $ticker + 1;
$sectionId = getBoardPart($printAllSections, 'id');
$sectionName = getBoardPart($printAllSections, 'title');
$sectionSlug = getBoardPart($printAllSections, 'slug');

?>
<dd><label for="<?php echo $sectionSlug; ?>">
<input type="checkbox" name="section[]" id="<?php echo $sectionSlug; ?>" value="<?php echo $sectionId; ?>" /> <?php echo $sectionName; ?></label></dd>
<?php } ?>

The list is populating as expected. But I want to be able to check to make sure that a user selects at least one of the checkboxes. I've searched here in SO and I only got the one that was done using JQuery, but I want to be able to do this verification using PHP

Community
  • 1
  • 1
Samuel Asor
  • 480
  • 8
  • 25
  • 1
    The only way you can do this purely in php would be AFTER the form is submitted, then it's just a matter of checking whether it's been set with `isset()` or `empty()` – Epodax Nov 05 '15 at 11:35
  • So, doing `if(empty["section[]"])` will solve the problem OR is there a specific way to do this @Epodax ? – Samuel Asor Nov 05 '15 at 11:43
  • No, you have to do it after the form is submitted on your `$_POST` (Or `$_GET`), PHP cannot validate client side. – Epodax Nov 05 '15 at 11:44
  • Exactly what I want to do (server side validation, just incase the user disables javascript in his/her browser). I understand that this will be done after the form is submitted, but my question is "how"? *Code snippets will be greatly appreciated.* – Samuel Asor Nov 05 '15 at 11:47
  • There are plenty of guides out there on how to do server side validation. – Epodax Nov 05 '15 at 11:48
  • I understand that. I know how to do a server side validation for a single checkbox. What I want to achieve is how to validate for this kind of multiple checkbox which has the same `input name="sections[]"`. – Samuel Asor Nov 05 '15 at 11:52
  • 2
    Yes, and `empty()` does that. If no checkbox is selected then no value is sent, i.e it will be empty – Epodax Nov 05 '15 at 12:02
  • Thanks. I've been able to get it done. I did `if(empty($_POST['sections])){ // do something}`. I think the problem I was having was on how to call the input name, since it was having `sections[]`. – Samuel Asor Nov 05 '15 at 12:23

2 Answers2

1

In the file, where your form is submitting (action file) add this condition:

if (empty($_POST['section'])) {
    // it will go here, if no checkboxes were checked
}
Legionar
  • 7,472
  • 2
  • 41
  • 70
0

In your action file, you should have the following

if(empty($_POST['section'])) {
    //this means that the user hasn't selected any checkbox, redirect to the previous page with error
}
itoctopus
  • 4,133
  • 4
  • 32
  • 44