PHP 使用 id 和选择更新多行


PHP update multiple rows with id and selects

此代码选取正确选中的复选框的 ID,但它从我的第一个选择中选择选择下拉列表,而不是我更改的下拉列表。有没有办法解决这个问题?我正在使用

<select name="status[]"><option value="1">active</option><option value="0">inactive</option></select>

这是我的进程代码。

if (isset($_POST['submit'])) {

// find out how many records there are to update
$size = count($_POST['id']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$id = $_POST['id'][$i];
$status= $_POST['status'][$i];
// do the update and print out some info just to provide some visual feedback
$query = "UPDATE users SET status = '$status' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
print "$status | $id<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
mysql_close();
}

我同意这些评论,但是,我只会对这个问题提供一个快速的答案。

为了HTML中的简单性,我会做这样的事情。 数组索引可以简单地从 PHP 中的计数器回显,或者静态输入,如果它不会根据其他任何内容而更改。 只需为每个项目增加此索引即可。

<input type="checkbox" name="id[0]" value="1"> Some Text
<select name="status[0]">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

现在对于 PHP

if (isset($_POST['submit'])) {
    foreach($_POST['id'] as $i=>$value) {
        if($value == 1) {
            // define each variable
            $id = $_POST['id'][$i];
            $status= $_POST['status'][$i];
            // do the update and print out some info just to provide some visual feedback
            $query = "UPDATE users SET status = '$status' WHERE id = '$id' LIMIT 1";
            mysql_query($query) or die ("Error in query: $query");
            print "$status | $id<br /><br /><em>Updated!</em><br /><br />";
        }
    }
    mysql_close();
}

编辑:

我忘了提到您可以将复选框的值设置为您需要的任何值。 只要确保if($value==1)检查有效的结果(例如>0您的所有ID都是阳性的(。