Validating multiple check boxes in PHP. Must check at least one but not more than three checkboxes

空扰寡人 提交于 2019-12-23 05:42:19

问题


I am using PHP to create a voting system and I have a form that I am inserting into MySQL database. I am going to use JavaScript to ensure that the user selects at least one candidate but not more than three, but I want to validate on the server side as well. Here is the web form for the page:

<form method="post" action="post.php">
<input type="checkbox" name="vote[FR01]" value="ON"> Freshman Candidate 1 <br />
<input type="checkbox" name="vote[FR02]" value="ON"> Freshman Candidate 2 <br />
<input type="checkbox" name="vote[FR03]" value="ON"> Freshman Candidate 3 <br />
<input type="checkbox" name="vote[FR04]" value="ON"> Freshman Candidate 4 <br />
<input type="checkbox" name="vote[FR05]" value="ON"> Freshman Candidate 5 <br />
<input type="checkbox" name="vote[FR06]" value="ON"> Freshman Candidate 6 <br />
<input type="submit" name="submit" value="submit">
</form>

I know I will need to use a for loop however, could anyone explain how I could use those array key indexes which are the column names in the database?


回答1:


How about this?

if (isset($_POST['submit'])) {
    $checkedCandidates = 0;
    $values = $_POST['vote'];
    $checkedCandidates = count($values);

    if ($checkedCandidates < 1) {
        echo 'You need to check at least one candidate.';
    } elseif ($checkedCandidates >= 4) {
        echo 'You can only check up to three candidates.';
    } else {
        echo 'Checked candidates: ' . var_dump($values);
    }
}



来源:https://stackoverflow.com/questions/21467253/validating-multiple-check-boxes-in-php-must-check-at-least-one-but-not-more-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!