user3399760
user3399760

Reputation: 27

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);
?> 

Upvotes: 0

Views: 316

Answers (2)

Anay Karnik
Anay Karnik

Reputation: 940

if($scanningvalue=='') $scanningvalue='off';

You added the code above, after the query instead you should add it just after setting the value of $scanningvalue and one more thing, the mysql_real_escape_string is not needed as you are setting the value and there is no question of a sql injection.

Upvotes: 2

Anay Karnik
Anay Karnik

Reputation: 940

Why don't you use radio buttons instead of checkboxes if you want a on/off?

Upvotes: 1

Related Questions