Insert Yes or No into MySQL based on checkbox valu

2020-07-30 03:16发布

问题:

I have a list of checkboxes that look like below, the numbers, 416, 419, etc represent a page number. They are for 2 sets of fields, one is "likebutton", the other is "sendbutton".

 <input type="checkbox" name="likebutton[]" value="416" />
 <input type="checkbox" name="likebutton[]" value="417" />
 <input type="checkbox" name="likebutton[]" value="418" />
 <input type="checkbox" name="likebutton[]" value="419" />
 ...more checkboxes
 <input type="checkbox" name="sendbutton[]" value="416" />
 <input type="checkbox" name="sendbutton[]" value="417" />
 <input type="checkbox" name="sendbutton[]" value="418" />
 <input type="checkbox" name="sendbutton[]" value="419" />
 ...more checkboxes

What I am trying to achieve is when these checkboxes get checked, I am able to update each row (page) with the data of either Yes (Checked) or No (Unchecked) for both likebutton and sendbutton fields in MySQL. Currently my mysql query look like something below. This seems to work only when I have one foreach function and if I tick off one or more checkboxes, but if i leave the codes as stated below or If I have everything unchecked, I get an error for the foreach function.

 foreach($_POST["likebutton"] as $pagenumberL)
 $YesNoL = isset($_POST["likebutton"]) ? 'Yes' : 'No';
 mysql_query("UPDATE pages SET likebutton='".$YesNoL."' WHERE page_id='".$pagenumberL."'");

 foreach($_POST["sendbutton"] as $pagenumberS)
 $YesNoS = isset($_POST["sendbutton"]) ? 'Yes' : 'No';
 mysql_query("UPDATE pages SET sendbutton='".$YesNoS."' WHERE page_id='".$pagenumberS."'");

Any pointer on my problem or better suggestion as to how I should proceed?

回答1:

The problem with checkboxes (as you have noted) is that unchecked ones do not submit any data.

The standard trick to get around this is...

<input type="hidden" name="field_name" value="0">
<input type="checkbox" name="field_name" value="1">

When the checkbox is checked, its value is submitted as it appears later in the document. If unchecked, the hidden input value is submitted.

You can then simply check the value by name

$field = isset($_POST['field_name']) ? $_POST['field_name'] : false;
$dbFlag = $field ? 'Yes' : 'No';

In your particular case, include the page_id in the input name, eg

<input type="hidden" name="likebutton[416]" value="0">
<input type="checkbox" name="likebutton[416]" value="1">

And in PHP

foreach ($_POST['likebutton'] as $pageId => $likeFlag) {
    $dbFlag = $likeFlag ? 'Yes' : 'No';

    // update DB
}