我正在尝试从带有复选框的HTML表单中获取输入。使用数据库中的student_ids创建复选框。像这样:
<td><input type="checkbox" name="{$row['STUDENT_ID']}" />
我想要做的是逐步浏览学生表并检查所有条目以检查哪些复选框。我想删除已使用复选框检查的数据库中的条目。
8 $query = "SELECT STUDENT_ID From Students";
9 $result = mysql_query($query) or die(mysql_error());
10 while($row=mysql_fetch_array($result)){
11 $checkname=$row['STUDENT_ID'];
12 foreach($_POST[$checkname] as $student_id =>val)
13 {
14 if($val == 'YES'
15 {
16 echo $_POST['STUDENT_ID'];
17 $query = "DELETE FROM Students WHERE STUDENT_ID" . mysql_real_escape_string($STUDENT_ID);
18 }
19 echo $query;
20 $result = mysql_query($query) or die(mysql_error());
21 //echo $POST['STUDENT_ID'];
22 }
23 }
答案 0 :(得分:1)
创建一个复选框数组:
<input type="checkbox" name="studentID[]" value="{$row['STUDENT_ID']}" />
来自PHP:
$studentID = $_POST['studentID'];
foreach($studentID as $ID){
echo $ID.'<br />'."\n";
}
编辑: 不确定,但我认为这是正确的方法:
$studentID = $_POST['studentID'];
$i=0;
foreach($studentID as $ID){
$i++;
echo $_POST['studentID'][$i].'<br />'."\n";
}
答案 1 :(得分:0)
请尝试以下表单:
<input type="checkbox" name="STUDENT_ID[<?php echo $row['STUDENT_ID'] ?>]" value="YES" />
这适用于您的PHP循环:
foreach ($_POST['STUDENT_ID'] as $student_id => $val) {
if ($val == 'YES') {
$query = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
$result = mysql_query($query) or die(mysql_error());
}
}
答案 2 :(得分:0)
更好的方法是从您提交的复选框中获取学生ID,然后对其执行删除操作。
HTML
<input type="checkbox" name="students_to_delete[]" value="{$row['STUDENT_ID']}" />
PHP
$students_to_delete = $_POST['students_to_delete'];
if(is_array($students_to_delete) && count($students_to_delete) > 0) {
$query = "DELETE FROM Students WHERE STUDENT_ID IN (" . implode(",", $students_to_delete) . ")";
$result = mysql_query($query) or die(mysql_error());
}
答案 3 :(得分:0)
上面的代码容易受到SQL注入攻击。如果有人将0 OR STUDENT_ID!=0
的值发回服务器,则学生表中的所有行都将被删除。
您的代码也效率低下 - 您将返回所有学生,然后迭代每个学生,看看是否需要删除。
您最好在标记中使用:
<input type="checkbox" name="STUDENT_TO_DELETE" value="$row['STUDENT_ID']" />
然后在php:
foreach ($_POST['STUDENT_TO_DELETE'] as $student_id => $val) {
$sql = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
mysql_query($sql);
}
}