如何使用循环使用复选框更新多个记录

时间:2013-03-14 17:07:18

标签: php mysql

我有一个更新表单,它使用循环来回显要更新的记录列表。它包括一个文本字段,“Sentences”和一个复选框,“Acceptable”。 我的foreach努力不起作用,并且正在吞噬数据列,所以是时候寻求帮助了。先生们和女士们,我该怎么写呢?

感谢您的帮助。

<?php 
if( isset($_POST["Sentences_ID"]) ) {
    foreach($_POST['Sentences_ID'] as $key=>$value) {
        $updateSQL = sprintf("UPDATE Sentences SET Sentences=%s, Acceptable=%s WHERE   Sentences_ID=$value",
            GetSQLValueString($_POST['Sentences'], "text"),
            GetSQLValueString($_POST['Acceptable'], "text"),
            ($_POST['Sentences_ID']));

        mysql_select_db($database_name, $name);
        $Result1 = mysql_query($updateSQL, $name) or die(mysql_error());
    }
}
?>


<?php
do {
?>
Sentence:<input type="hidden" name="Sentences_ID[]" id="Sentences_ID[< ?php echo     $row_rsCounting['Sentences_Id'];?>]" value="<?php echo $row_rsCounting['Sentences_Id'];?>"   />

Acceptable:<input type="checkbox" name="Acceptable" id="Acceptable"     value="Acceptable"/></label> | 
<input type="text" name="Sentences" id="Sentences" value="< ?php echo     $row_rsCounting['Sentences'];?>" size="50" />
<?php
} while ($row_rsCounting = mysql_fetch_assoc($rsCounting));
?>

2 个答案:

答案 0 :(得分:1)

可接受和句子输入也需要是数组,例如name =&#34; Acceptable []&#34;。然后你可以在你的PHP循环中访问它们,如$ _POST [&#39; Acceptable&#39;] [$ key]。但是,我不认为可以保证多个输入数组的顺序相同,因此我建议在输入名称中使用Sentence ID。为所有输入做到这一点。

像这样......

<?php 
if( isset($_POST["Sentences_ID"]) ) {
    foreach($_POST['Sentences_ID'] as $key=>$value) {
        $updateSQL = sprintf("UPDATE Sentences SET Sentences=%s, Acceptable=%s WHERE   Sentences_ID=$value",
            GetSQLValueString($_POST['Sentences'][$key], "text"),
            GetSQLValueString($_POST['Acceptable'][$key], "text"),
            ($value));

        mysql_select_db($database_name, $name);
        $Result1 = mysql_query($updateSQL, $name) or die(mysql_error());
    }
}
?>


<?php
do {
?>
Sentence:<input type="hidden" name="Sentences_ID[< ?php echo  $row_rsCounting['Sentences_Id'];?>]" id="Sentences_ID[< ?php echo     $row_rsCounting['Sentences_Id'];?>]" value="<?php echo $row_rsCounting['Sentences_Id'];?>"   />

Acceptable:<input type="checkbox" name="Acceptable[< ?php echo     $row_rsCounting['Sentences_Id'];?>]" id="Acceptable" value="Acceptable"/></label> | 
<input type="text" name="Sentences[< ?php echo $row_rsCounting['Sentences_Id'];?>]" id="Sentences" value="< ?php echo $row_rsCounting['Sentences'];?>" size="50" />
<?php
} while ($row_rsCounting = mysql_fetch_assoc($rsCounting));
?>

答案 1 :(得分:0)

我的第一个建议是做一些调试。

foreach($_POST['Sentences_ID'] as $key=>$value) {

print_r($_POST['Sentences_ID']);die;

这可以让您深入了解您尝试迭代的变量的结构