简体   繁体   中英

Update table from multiple checkboxes

I want to update a table from multiple checkboxes with dynamic fields.

I built the checkboxes with the below code:

<div class="form-horizontal" style="margin-right: 35px; margin-left: 0px;">
<div class="form-group">
<?  $i = 0; 
    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="<?= $title ?>" name="<?= $title ?>" type="checkbox" <?= $value=='on' ? 'checked' : ''?> />
            </div>
        </div>
    <? $i++;
        if($i % 4 == 0) { ?> 
    </div>
    <div class="form-group"> 
        <?} 
    }?>
</div>

So i get this as i want it. 预习

When i submit my form i run a function that gets all the fields from the table specifics and tries to update the table with the changes from the form (checkbox)

foreach ($row_specifics as $title => $value) {
    $valueToInsert = ( isset($_REQUEST[$title]) ) ? $value : null;

    if( $valueToInsert ) {
        $query = mysql_query("UPDATE `specifics` SET $title = '{$valueToInsert}' WHERE `car_id`= $id");
    }
}
  • When i change the form to POST and i submit test changes, nothing happens.
  • When i change the form to GET and i submit test changes, i get only the on values in URL query.

I tried to echo the $title and $valueToInsert inside if to check the problem (in POST ) but i get only three values [ ABS on / ESP on / Immobilizer on ].

REQUEST: I want to update the table correctly, when someone change the checkbox options. This form and checkbox is at the Edit Panel of an administration page and the user edit the specifications of a record in table.

You should check to see if all of your values are coming through as expected. Try the following code to view all of the $_REQUEST information:

$_REQUEST['someRequest'] = 'sweet';
$output = 'Requests:<pre>';
ob_start();
var_export($_REQUEST);
$output .= ob_get_contents();
ob_end_clean();
$output .= '</pre>';
print $output;

I suggest prefixing all of your form fields so you can more easily detect them in the requests. For example:

<input id="<?= 'chickenButter' . $title ?>" name="<?= $title ?>" type="checkbox" />

And then check for 'chickenButter' in the requests:

$_REQUEST['chickenButterCheerios'] = 'sweet';
foreach($_REQUEST as $key => $value){
    if(stristr($key,'chickenButter')){
        $output .= $value;
    }
}
print $output;//prints sweet

Once you get all of your expected values, be aware of how to determine and store the state of each switch. See this question for more.

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