首页 > 解决方案 > PHP - 如何获取多个复选框的值以及输入类型

问题描述

I wanted to create an error when a specific value of $_POST['MAG'] is selected and the input type next to it isn't given.

我尝试使用其他方法,例如 if、else、foreach、for,但我似乎仍然无法获得正确的编码。我真的需要帮助。

这是我第一次编码,我正在参加在线课程,所以很难从同学或老师那里获得帮助

 <form method="post" action="">

  Select which magazine and type qty of subscriptions:<br><br>

  <input type="checkbox" name="MAG[]" value="TREASURE"><b>Treasure Magazine</b> | Qty of Subscriptions: <input type="number" name="TNUMSUBS" size="5px">
  <br>

  <input type="checkbox" name="MAG[]" value="VESSEL"><b>Vessel Magazine</b> | Qty of Subscriptions: <input type="number" name="VNUMSUBS" size="5px">
  <br>

  <input type="checkbox" name="MAG[]" value="MECH"><b>MECH Magazine</b> | Qty of Subscriptions: <input type="number" name="MNUMSUBS" size="5px">
  <br><br>

  <p><input type="submit" name="submit"></p>

</form>


<?php
if (isset($_POST["submit"]))
{
$vNumSubs = $_POST['VNUMSUBS'];
$tNumSubs = $_POST['TNUMSUBS'];
$mNumSubs = $_POST['MNUMSUBS'];

    if(empty($_POST["MAG"]))
    {
        print "You didn't select a magazine";

        foreach($_POST['MAG'] as $magazine)
        {

            if($magazine == "TREASURE" && empty($tNumSubs))
            {
            print "type quantity";
            }

            if($magazine == "VESSEL" && empty($vNumSubs))
            {
                print "type quantity";
            }

            if($magazine == "MECH" && empty($mNumSubs))
            {
                print "type quantity";
            }
        }
    }


}

我尝试使用 empty(),但我很难让它显示出来。请帮忙

标签: phpcheckbox

解决方案


foreach在执行的块中,当$_POST['MAG']它为空时,所以没有什么可以循环的(它实际上会得到一个错误,因为$_POST['MAG']undefined没有选中任何框时,你不能使用foreach它)。

它应该在else块中。

if(empty($_POST["MAG"])) {
    print "You didn't select a magazine";
} else {
    foreach($_POST['MAG'] as $magazine)
    {
        if($magazine == "TREASURE" && empty($tNumSubs))
        {
            print "type quantity";
        }

        if($magazine == "VESSEL" && empty($vNumSubs))
        {
            print "type quantity";
        }

        if($magazine == "MECH" && empty($mNumSubs))
        {
            print "type quantity";
        }
    }
}

但也许你不应该打扰复选框。让他们填写每本杂志的数量,用0表示他们不想要那本杂志。


推荐阅读