从表单中获取数组

从表单中获取数组

问题描述:

I have a form that uses a checkbox and it gets all the data from the mysql database. So there could be from 1 to unlimited of the checkboxes.

I need to get each of those that are checked when the form is submitted.

It works if all of them are checked, but if only a few are checked, it will either show none or just one of them.

Here is the code I am using to show the checkboxes with data:

while ($myrow = mysqli_fetch_array($result)){
echo<<<END
<input type="checkbox" id="units" name="unit[$i]" value="$myrow[unit_id]" /> $myrow[unit_id]<br />
END;
$i++;
}//end while

Here is the code I am using when the form is submitted:

$i=0;
while($_POST["unit"][$i] != ""){
$unit = $_POST["unit"][$i];
$unit = $res2->real_escape_string($unit);
echo $unit."<br />";
$i++;
} // end while

I believe the problem is the fact that I have while($_POST["unit"[$1] != "") and if one box is checked and then another one 2 or 3 down is checked, it sees the 2nd one empty and stops.

If that's the case, I need help to figure out how to make it run through them all and print out the ones that were checked. Remember, there could be anywhere from 1 to unlimited checked so it can't be a set number like while($i <= 50)

Thank you!

我有一个使用复选框的表单,它从mysql数据库中获取所有数据。 因此,复选框可以从1到无限制。 p>

我需要获取提交表单时检查的每一个。 p>

如果检查了所有这些,它就可以工作,但如果只检查了几个,它将显示无或只显示其中一个。 p>

这是我用来显示复选框的代码 数据: p>

  while($ myrow = mysqli_fetch_array($ result)){
echo&lt;&lt;&lt; END 
&lt; input type =“checkbox”id =“units  “name =”unit [$ i]“value =”$ myrow [unit_id]“/&gt;  $ myrow [unit_id]&lt; br /&gt; 
END; 
 $ i ++; 
} //结束时
  code>  pre> 
 
 

这是我正在使用的代码 表单提交时: p>

  $ i = 0; 
while($ _ POST [“unit”] [$ i]!=“”){
 $ unit =  $ _POST [“unit”] [$ i]; 
 $ unit = $ res2-&gt; real_escape_string($ unit); 
echo $ unit。“&lt; br /&gt;”; 
 $ i ++; 
}  //结束时
   code>  pre> 
 
 

我认为问题在于我有 while($ _ POST [“unit”[$ 1]!=“”) code>如果选中一个方框,然后检查另一个方框2或3,则会看到第二个方框为空并停止。 p>

如果是这种情况,我需要帮助来弄清楚如何让它贯穿全部并打印出已检查的那些。 请记住,可能存在从1到无限制的任何位置,因此它不能像那样的设定数字($ i&lt; = 50) code> p>

谢谢 ! p> div>

Checkboxes are only sent when they are checked. With while the loop stops as soon as a checkbox denoted by $_POST['unit'][$i] is not set, so the rest never get evaluated. You should consider using foreach for arrays:

foreach($_POST["unit"] as $unit) {
    echo $unit . "<br />";
}

If the key is important:

foreach($_POST["unit"] as $key => $unit) {
    echo $key . " is " . $unit . "<br />";
}

If $i is not important you should use :

name="unit[]"

and afther retrieve the values in a foreach loop

foreach ( $_REQUEST['unit'] as $unit ) ....