如何使用带有php mysql的复选框更新数据库中的多个更新
<form action="enableprofile1.php" method="post">
//user id
<input type="hidden" name="id1[]" id="id1[]" value="<?php echo $sn; ?>" />
//user id
//enable checkbox
<input type="checkbox" name="enable[]" id="enable[]" value="1" <?php if($en=='1'){ echo 'checked';} ?> />
//enable checkbox
<input type="submit" name="save" value="Save" class="fontBold">
</form>
我可以知道,当我取消检查复选框时,我可以像0那样存储价值吗
答案 0 :(得分:0)
/* */
1
。我希望不是。我还假设这些复选框的值来自您的数据库。您的enableprofile1.php应如下所示:
<?php
/* ESTABLISH CONNECTION */
$con = new mysqli("YourHost", "YourUsername", "YourPassword", "yourDataBaseName"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST["save"])){ /* IF SAVE BUTTON IS CLICKED */
/* STORE THE PASSED DATA FROM YOUR FORM VIA POST */
$enable = $_POST["enable"];
$hiddenid = $_POST["id1"];
$total = count($enable); /* COUNT TOTAL ARRAY */
for($x=0;$x<=$total;$x++){ /* RUN A LOOP THAT CHECKS ALL DATA */
if(!empty($enable[$x])){ $todo=1; } /* IF ENABLE IS CHECKED */
else { $todo=0; } /* IF ENABLE IS NOT CHECKED */
$stmt = $con->prepare("UPDATE yourTable SET yourColumn = ? WHERE yourID = ?"); /* REPLACE NECESSARY CONNECTION VARIABLE, TABLE NAME AND COLUMN NAME */
$stmt->bind_param('ss', $todo, $hiddenid[$x]); /* BIND PASSED DATA TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
} /* END OF FOR LOOP */
} /* END OF ISSET SAVE */
?>
将此添加到您的表单:
...
<?php
$counter=0;
//user id
echo '<input type="hidden" name="id1[$counter]" id="id1[]" value="'.$sn.'" />';
// user id
//enable checkbox
echo '<input type="checkbox" name="enable[$counter]" id="enable[]" value="1" if($en=='1'){ echo 'checked';} />';
$counter=$counter+1; /* INCREMENT $counter FOR EVERY LOOP */
?>
...