使用复选框更新数据库列

时间:2016-07-26 21:14:57

标签: php mysql mysqli

echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">";
    if ($isAdmin === '1'){
        echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" checked=\"checked\" value=\"1\" />";
    } else {
        echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" value=\"0\" />";
    }
    echo "<input type=\"submit\" name=\"formSubmit\" value=\"X\" />";
echo "</form>";

上面的代码在while循环中,因此它为每个用户创建一个表单。我的PHP代码如下所示:

$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
    $status = $_POST['checkbox'];
}

$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
$stmt->bind_param('s', $status);

$stmt->execute();

$stmt->close();
$mysqli->close();

如果没有实际将表单提交给服务器,为什么管理员用户只需刷新页面就成为非管理员用户?

更新后的代码:

?>

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
    <input type="checkbox" id="checkbox" name="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
    <input type="hidden" id="userid" name="userid" value="<? echo $members_row['id']; ?>" />
    <input type="submit" id="submit" name="submit" value=">>" />
</form>

<?

$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
    $status = $_POST['checkbox'];
    $id = $_POST['id'];

    $stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
    $stmt->bind_param('s', $status);

    $stmt->execute();

    $stmt->close();
    $mysqli->close();
}

1 个答案:

答案 0 :(得分:0)

结合一些事情,将你的括号移到php片段的末尾,然后检查帖子是否已设置,但不是等于任何东西。 $status将用于在发布时更新它。旁注,由于表单处于循环中,id="checkbox"在使用javascript时会出现问题。 id="*"应该是唯一的,以便提供价值。最后,$id的来源在提供的脚本中是未知的,您还需要确保bind_param对该值也是如此(也许应该由帖子提供?)。不确定该变量的来源如此难以评论。

$checked = ($isAdmin == '1');
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
    <input id="checkbox" name="checkbox" type="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
    <input type="submit" name="formSubmit" value="X" />
</form>
<?php //continue with loop

由于您的表单引用PHP_SELF

,因此这可能位于顶部
<?php
if (isset($_POST['checkbox'])) {
    $status = $_POST['checkbox'];
    // The $id variable is suspect here. Probably should be provided by the post?
    $stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = '$id'");
    $stmt->bind_param('s', $status);
    $stmt->execute();
    $stmt->close();
    $mysqli->close();
}

如果我这样做,我会使用函数或类/方法使其更具人性化和可重用性:

function updateUserRole($id,$status,$mysqli)
    {
        $stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = ?");
        $stmt->bind_param('si', $status,$id);
        $stmt->execute();
        $stmt->close();
    }

// To execute, include the function
// then run the "if" condition
if (isset($_POST['checkbox']))
    updateUserRole($_POST['id'],$_POST['checkbox'],$mysqli);