验证PHP中的多个复选框。必须至少选中一个但不超过三个复选框

编程入门 行业动态 更新时间:2024-10-23 17:25:11
本文介绍了验证PHP中的多个复选框。必须至少选中一个但不超过三个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用PHP创建投票系统,我有一个表单,我插入到MySQL数据库。我将使用JavaScript来确保用户至少选择一个候选,但不超过三个,但我想在服务器端验证。以下是网页的网络表单:

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>

我知道我需要使用一个for循环,但是任何人都可以解释如何使用这些数组键索引是数据库中的列名称?

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?

推荐答案

如何?

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); } }

更多推荐

验证PHP中的多个复选框。必须至少选中一个但不超过三个复选框

本文发布于:2023-11-04 01:01:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复选框   多个   但不   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!