Exception or error:
I’m creating a PHP panel where the Admin can turn on/off different features on the website. The problem with my code is that everytime I switch the button, the value won’t update. Whenever I toggle it, it should save the value in the databse and the switch itself should remain turned on/off.
I’m going to attach some photos and the code. If anything is unclear I can explain further.
<form method="post">
<label class="switch">
<input type="checkbox" id="maintenance" name="maintenance">
<div class="slider round">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
</label>
<input type="submit" name="submit" value="Submit" >
</form>
And the PHP code
EDIT: The query now works, but the button won’t remain on or off
$value = $_POST['maintenance'];
if(isset($_POST['submit']) ){
if(isset($_POST['maintenance'])){
$value = 1;
}else{
$value = 0;
}
$stmt = $mysqli->prepare("UPDATE settings SET maintenance = ? WHERE id = 1");
$stmt->bind_param('i', $value);
$stmt->execute();
}
EDIT – WORKING VERSION
if(isset($_POST['submit']) ){
if(isset($_POST['maintenance'])){
$_POST['maintenance'] = 1;
}else{
$_POST['maintenance'] = 0;
}
if(isset($_POST['campaign'])){
$_POST['campaign'] = 1;
}else{
$_POST['campaign'] = 0;
}
$stmt = $mysqli->prepare("UPDATE settings SET maintenance = ?, campaign = ? WHERE id = 1");
$stmt->bind_param('ii', $_POST['maintenance'], $_POST['campaign']);
$stmt->execute();
}
$stmt = $mysqli->prepare("SELECT maintenance, campaign FROM settings WHERE id = 1");
$stmt->execute();
$stmt->bind_result($status_m, $status_s);
$stmt->fetch();
$stmt->close();
}
And the HTML
<form method="post">
<label class="switch">
<?php if($status_m == 1){?>
<input type="checkbox" id="maintenance" name="maintenance" checked>
<?php }else{?>
<input type="checkbox" id="maintenance" name="maintenance">
<?php } ?>
<div class="slider round">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
</label>
<label class="switch">
<?php if($status_s == 1){?>
<input type="checkbox" id="campaign" name="campaign" checked>
<?php }else{?>
<input type="checkbox" id="campaign" name="campaign">
<?php } ?>
<div class="slider round">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
</label>
<button type="submit" class="float-right button" name="submit" >Save</button>
</form>
How to solve: