我的PHP脚本有一个非常随机的问题。我正在显示一些复选框,以使用Raspberry Pi打开和关闭我的灯。我不是PHP的新手,但是我是使用复选框并设置其值的新手。
问题在于,当我选中该复选框时,PHP脚本选择了复选框中的随机值之一,而不是我选择的那个。
我的代码当前没有SQL保护,我必须首先找到问题。
我的代码头:
<?php
if(isset($_POST['lamp'])){
$lamp = $_POST['lamp'];
echo $lamp;
$statusSQL = mysqli_query($connect, "SELECT * FROM lamps WHERE name='$lamp' LIMIT 1");
$statusFetch = mysqli_fetch_array($statusSQL);
$lampStatus = $statusFetch['status'];
$lampID = $statusFetch['id'];
if ($lampStatus){
$sql = "UPDATE lamps SET status='0' WHERE id='$lampID'";
if ($connect->query($sql) === TRUE) {
echo "Lamp is off";
}
}
else{
$sql = "UPDATE lamps SET status='1' WHERE id='$lampID'";
if ($connect->query($sql) === TRUE) {
echo "Lamp is on";
}
}
}
?>
获取复选框
<form id="checkForm" method="post" action="dashboard.php">
<?php
$sql = "SELECT * FROM lamps";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='row'>";
if ($row["status"]){
?>
<div class='col-xs-4'><label class='switch'>
<input id="lamp" name="lamp" value="<?php echo $row["name"]; ?>" onclick="document.getElementById('checkForm').submit()" type='checkbox' checked>
<span class='slider round'></span>
</label></div><br>
<?
}
else{
?>
<div class='col-xs-4'><label class='switch'>
<input id="lamp" name="lamp" value="<?php echo $row["name"]; ?>" onclick="document.getElementById('checkForm').submit()" type='checkbox'>
<span class='slider round'></span>
</label></div><br><?
}
echo "</div>";
}
} else {
echo "No lamp active in database";
}
?>
</form>