简体   繁体   中英

Checkbox / Switch not functioning properly

I have a switch on a php page with the code:

<form action="onoff-switch.php" method="post">
<div class="onoffswitch">
    <input type="checkbox" 
               name="onoffswitch" 
               class="onoffswitch-checkbox" 
               id="myonoffswitch" checked 
               value="on">
    <label class="onoffswitch-label" for="myonoffswitch">
        <div class="onoffswitch-inner"></div>
        <div class="onoffswitch-switch"></div>
    </label>
</div>
 <input type="submit" name="formSubmit" value="Submit" />
</form>

which when checked is supposed to send a value of ON or OFF the the php page onoff-switch.php. Two problems, Line 15 is not needed, however, the form does not submit any value unless it is there. Taking away line 15, when I check or uncheck the box, then it is supposed to submit by itself. It does not.

Additionally, the onoff-switch.php gives the feedback of a value "OFF", which I have no clue where it gets it from since "OFF" is nowhere in the code. Of course that should be the value if the box is not checked.

Question is where is this checkbox going wrong?

PHP Code:

<?php
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


if (isset($_POST['formSubmit']))
{
    // escape variables for security
    $scanningvalue = mysqli_real_escape_string($_POST['onoffswitch']);

    $sqlon="INSERT INTO configuration (scanning) VALUES ('$scanningvalue')";
    $result=mysqli_query($con, $sqlon);
    if($scanningvalue=='') $scanningvalue='off';
       if($result)
    {
       echo "The db operation done (1 record added) and switch value ".$scanningvalue;
    }
else
{
   echo "The db operation error and switch value ".$scanningvalue;
}

}

mysqli_close($con);
?> 
if($scanningvalue=='') $scanningvalue='off';

您已在上面添加了代码,在查询之后,应改为在设置$ scanningvalue值和其他内容之后添加它,不需要mysql_real_escape_string,因为您正在设置该值,因此没有SQL注入的问题。

如果要打开/关闭,为什么不使用单选按钮而不是复选框?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM