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

8
  • 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() Commented Nov 5, 2015 at 11:35
  • So, doing if(empty["section[]"]) will solve the problem OR is there a specific way to do this @Epodax ? Commented Nov 5, 2015 at 11:43
  • No, you have to do it after the form is submitted on your $_POST (Or $_GET), PHP cannot validate client side. Commented Nov 5, 2015 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. Commented Nov 5, 2015 at 11:47
  • 2
    Yes, and empty() does that. If no checkbox is selected then no value is sent, i.e it will be empty Commented Nov 5, 2015 at 12:02

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your effort. I've been able to rectify the error.
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
}

1 Comment

Thank for your effort and editing. The issue has been resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.