I got a checkbox and i want to pass all the values into a function in order to update a table.
The checkbox has 60 options and i generate them with a foreach() from mysql.
// html form
<div class="form-group">
<? $i = 0;
foreach ($row_specifics as $title => $value) {
if ($value =='on') { ?>
<label class="control-label col-lg-2"><?= $title ?></label>
<div class="col-lg-1" style="padding-right: 5px; padding-left: 0px;">
<div class="make-switch switch-small" data-on="success" data-off="danger">
<input id="specs_value" name="<?= $title ?>" type="checkbox" value="on" checked/>
</div>
</div>
<? } else { ?>
<label class="control-label col-lg-2"><?= $title ?></label>
<div class="col-lg-1" style="padding-right: 5px; padding-left: 0px;">
<div class="make-switch switch-small" data-on="success" data-off="danger">
<input id="specs_value" name="<?= $title ?>" type="checkbox" value="off"/>
</div>
</div>
<?} $i++;
if($i % 4 == 0) { ?>
</div>
<div class="form-group">
<?} }?>
// function
foreach ($row_specifics as $title => $value) {
$value = $_REQUEST[$title];
$query = mysql_query("UPDATE `specifics` SET $title = '$value' WHERE `car_id`= $id");
}
QUESTION: How can i get the title and the value from $_POST
and use it in the function and the update query ?
The $_POST
gets only the values that are 'on'. Not the 'off'. I could either get them all or just get the title from value with the value in order to use it in the query.
In your loop verify with isset if $_POST['title']
exist, that means checkbox is on:
foreach ($row_specifics as $title => $value) {
$valueToInsert = ( isset($_POST[$title]) ) ? $value : null;
if( $valueToInsert ) {
$query = mysql_query("UPDATE `specifics` SET $title = '{$valueToInsert}' WHERE `car_id`= $id");
}
}
Not on topic but not exactly off topic... You could simplify your code to make it more manageable and easier to read.
<? foreach ($row_specifics as $title => $value): ?>
<label class="control-label col-lg-2"><?= $title ?></label>
<div class="col-lg-1" style="padding-right: 5px; padding-left: 0px;">
<div class="make-switch switch-small" data-on="success" data-off="danger">
<input id="specs_value" name="<?= $title ?>" type="checkbox" value="<?= $value?>"<?= $value=='on' ? 'checked' : ''?>/>
</div>
</div>
<? endforeach ?>
This will remove the need for the if statement and the block of repeated code.