dongtan3395 2014-01-30 20:58
浏览 84

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

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条回答 默认 最新

  • donglaoe2979 2014-01-30 21:33
    关注

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

    Preview

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line