PHP/HTML : How to access checkboxes dynamically generated in loop - php

I have checkboxes which is generated in while loop. These checkboxes are always checked for the first time and the value stored in the database is "On". But when user unchecks it, I want to store "Off" in database. But my problem is i am not able to access the checkbox name to check if which checkboxes are unchecked on button click. I wrote this code
while($row = mysql_fetch_assoc($result)) {
if($pck_id_renew == 'On')
{
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
checked="checked" style="width:50px" value="On"/></td>';
}
if($pck_id_renew == 'Off') {
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
style="width:50px" value="Off"/></td>';
}
}

You will only receive the input value of checkboxes that are checked. Use an array and store all available checkbox names in it. Loop through this array to detect which checkboxes are checked/unchecked.
Code may look something like this:
// Define available checkboxes
$inputs = array('renew_chk', ...);
// Check input values
$values = array();
foreach ($inputs as $input) {
if (isset($_POST[$input])) {
$values[$input] = 'On';
}
else {
$values[$input] = 'Off';
}
}
// Loop through $values and store value in database
foreach ($values as $input => $value) {
// UPDATE database SET $input = $value WHERE id = [n];
}

Related

How to verify multiple checkboxes using php

I have a list which I am populating from my DB into multiple checkboxes using a foreach loop:
<?php
$sections_arr = listAllForumBoards(0, 1, 100);
$count_board = count($sections_arr);
$ticker = 0;
foreach($sections_arr as $key => $printAllSections){
$ticker = $ticker + 1;
$sectionId = getBoardPart($printAllSections, 'id');
$sectionName = getBoardPart($printAllSections, 'title');
$sectionSlug = getBoardPart($printAllSections, 'slug');
?>
<dd><label for="<?php echo $sectionSlug; ?>">
<input type="checkbox" name="section[]" id="<?php echo $sectionSlug; ?>" value="<?php echo $sectionId; ?>" /> <?php echo $sectionName; ?></label></dd>
<?php } ?>
The list is populating as expected. But I want to be able to check to make sure that a user selects at least one of the checkboxes. I've searched here in SO and I only got the one that was done using JQuery, but I want to be able to do this verification using PHP
In the file, where your form is submitting (action file) add this condition:
if (empty($_POST['section'])) {
// it will go here, if no checkboxes were checked
}
In your action file, you should have the following
if(empty($_POST['section'])) {
//this means that the user hasn't selected any checkbox, redirect to the previous page with error
}

Create variable from table cells

I need your help to figure this out.
I have a table (link on top) of prices for typographic company. Let's say, to print business cards. My goal is to create a system where customer can press on a price and confirmation popup will appear with information from table.
For example: I need 500 business cards with Option #1.
I press on the price 740 and popup window appears with info: "You have ordered 500 business cards with Option #1 by price 740.
Manually I can create all variations like (row-1, cell-5) + (row-3, cell-1) + (row-3, cell-5) but this is not an options, even though the logic is right.
I have a table and popup already created and working. All prices are variables and I can change them from my back-end. I need help with combining variables.
How can I achieve my goal using php?
You need JavaScript to do a popup, not PHP. You can use PHP to create an array for JavaScript to use to retrieve the values.
In this example I am creating a JavaScript array ($JS) that will have the same values as the displayed table.
In the Table I add buttons to each cell (I use buttons because the default style display is inline-block and their purpose is to be clicked) where when selected will pass the row,column of the table.
$JS = 'var cells['; // initialize JavaScript array
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo "
<tr><td><button type="button" onclick="sel($ndx,0)">$row[0]</button></td>
<td><button type="button" onclick="sel($ndx,1)">$row[1]</button></td>
<td><button type="button" onclick="sel($ndx,2)">$row[2]</button></td>
<td><button type="button" onclick="sel($ndx,3)">$row[3]</button></td>
<td><button type="button" onclick="sel($ndx,4)">$row[4]</button></td><tr>";
$JS .= [$ndx[$row[0],$row[1],$row[2],$row[3],$row[4],$row[5]][";
$ndx++;
}
echo '</table>'
$JS = substr($JS,0,-1) . ']]'; // trim the trailing `[` and close the array
echo <<<EOT
<script type="text/javascript">//<![CDATA[
$JS
function sel(r,c){
var selected = cells[r,c];
}
//]]>
</script>
EOT;
The main thing I wanted to show in the above is how PHP can pass values to JavaScript. It is not really needed as you could just pass the value in the sel($ndx,0,$row[x]) where x is the column number in the table
But there is a better way that would be more user friendly:
This example the user makes selections by checking the check box. The form is submitted (to same script) for confirmation.
There is a hidden input where name=sub and value=1. so when the confirm is clicked this can be checked by checking the value of $_POST['sub']
$sub = intval($_POST['sub']);
if($sub == 1){
$selections = array();
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
}
}
// Confirmation (e.g. create popup box) code goes here
}
.
echo '<form action="???.php" method="post"><div><table>';
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo <<<EOT
<tr><td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\"/>$row[0]</div></td>
<td><div id="d$ndx1"<input type="checkbox" name=\"c$ndx1\" value=\"$row[1]\"/>$row[1]</div></td>
<td><div id="d$ndx2"<input type="checkbox" name=\"c$ndx2\" value=\"$row[2]\"/>$row[2]</div></td>
<td><div id="d$ndx3"<input type="checkbox" name=\"c$ndx3\" value=\"$row[3]\"/>$row[3]</div></td>
<td><div id="d$ndx4"<input type="checkbox" name=\"c$ndx4\" value=\"$row[4]\"/>$row[4]</div></td>
EOT;
}
echo '</table><input type="submit" value="Confirm Selections"/><input type="hidden" name="sub" value="1"/></div></form>';
To style the checked check boxes:
Add an onclick event to each check box
<input type="checkbox" name=\"c$ndx0\" value=\"$row[0] onclick=\"chk($ndx0)\" \>
Then this JavaScript will change the background color of the div which encapsulates the check box giving visual feedback to the user.
The init() function creates an array for each check box eliminating the document.getElementById() each time a check box is checked or unchecked
It also colors the background based on whether the checkbox is checked or not.
<script type="text/javascript"> //<![CDATA[
var div=0;
var c = new Array;
var d = new Array;
toggle = new Array;
toggle[true] = 'checked="checked"';
toggle[false] = '';
bg = new Array;
bg[true] = '#f00';
bg[false] = '#2985EA';
function chk(id){
d[id].style.backgroundColor=bg[c[id].checked];
}
function init(){
var checked,did;
var divs = document.getElementsByTagName("div");
for (div=0; div<divs.length; div++){
did = divs[div].getAttribute("id");
if (did != null){
if (did.substring(0,1) == "d"){
var i = did.substring(1,3);
c[i] = document.getElementById('c' + i);
d[i] = document.getElementById('d' + i);
checked = c[i].checked;
d[i].style.backgroundColor=bg[checked];
}
}
}
}
window.onload = init;
//]]>
</script>
Then when the form is submitted for confirmation you can check the selected check boxes by adding $checked to each checkbox
<td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\" $checked[$ndx0] />$row[0]</div></td>
Then add $checked["$val"] = 'checked="checked"'; to the $_POST loop
$checked = array();
$sub = intval($_POST['sub'];
if($sub == 1){
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
$checked["$val"] = 'checked="checked"';
}
}
}

PHP arrays from form input

I have some data in a html table which has been populated from a mysql database. To put the data into the html table I have done the following:
$meterdetail = getMeterDetails($ticketNumber);
This gets a number of records from the mysql table Then for each record retrieved from the db I do the following..
foreach ($meterdetail as $v2) {
<tr>
<td class='tableText'>
<input type='hidden' name='ids[]' value='".$v2['id']."'>
<input type='text' name='meters[]' value=''>
</td>
</tr>
Ultimately what I am trying to do here is update each record (based on the ID from the mysql table) with the values in the input of the table.
When I click on a submit button I need to step through each record that was collected and insert the value that was typed into the html form corresponding to the relevant id.
To process the $_POST data I do the following
if (!empty($_POST['meters']) && !empty($_POST['ids'])) {
for ($i = 0; $i < count($_POST['meters']); $i++) {
updateRecord($_POST['ids'][$i],$_POST['meters'][$i]);
}
}
This seems to be working but for some reason I don't feel comfortable with this solution so my question is: Is there a better (more elegant / more correct) way to do this (particularly the processing of the 2 $_POST arrays)? Can I create one associative array with the ID as key and the form input value as the corresponding value?
$met = $_POST['meters'];
$id = $_POST['ids'];
if (isset($met) && isset($id))
{
for ($i = 0; $i < count($id); $i++)
{
updateRecord($id[$i],$met[$i]);
}
}
A better way is to make sure you have 'set in stone' names for your inputs;
foreach ($meterdetail as $key => $v2) {
echo "
<tr>
<td class='tableText'>
<input type='hidden' name='id_".$key."' value='".$v2['id']."'>
<input type='text' name='meter_".$key."' value=''>
</td>
</tr>
";
}
And than process the post-data as such:
$ids = array();
$meters = array();
foreach($_POST as $name => $value) {
if(strpos($name, 'id_') === 0) {
$ids[substr($name, 3)] = $value;
}
if(strpos($name, 'meter_') === 0) {
$ids[substr($name, 3)] = $value;
}
}
if(count($ids) && count($meters)) {
foreach($ids as $key => $id) {
updateRecord($id, $meters[$key]);
}
}
This way you are always sure you have accompanying values which you are updating in the db.
PS: this is proof of concept... haven't tested it yet...

Is there a way of updating a large form with checkboxes effectively?

Having an issue updating a large form with checkboxes effectively to database.
Just for illustration:
<form action="save.php" method="post">
<?php
for {$i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="product-' . $i . '">';
}
<input type="submit">
</form>
<?php
$posted_values = $_POST;
foreach($posted_values as $key=>$p) {
$chkbox = $posted_values[$p];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for each posted value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
Is there any way of just adding changed checkboxes to the save_dbarray? (Only checked boxes would be posted to $_POST, but I want unchecked values to be a part of the update as well if they have changed) I have to do some expensive checking for each posted value, therefore
UPDATE
I dont want to have loop through all 1000 checkboxes. I just want to loop through the changed (from checked to unchecked or from unchecked to checked) checkboxes, but in above case $posted_values would only return checkboxes that has checked values (from unchecked to checked)
<?php
//I DONT want to have to do like this:
for {$i=0;$i<1000;$i++) {
$prodnr = 'product-' . $i;
$chkbox = $_POST[$prodnr];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for every value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
You can use HTML array inputs and PHP to do the same.
A sample code will be like below.
<form action="save.php" method="post">
<?php
for ($i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="products[]" value="' . $i . '"> '. $i .'<br>';
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['products']); // Will contain your desired output
foreach($_POST['products'] as $i) {
$save_dbarray[$i] = 'on'; // 'on' or whatever value if you need.
// Actually you just need $_POST['products'], no need for this loop.
}
print_r($save_dbarray);
?>
EDIT
You need to loop through $_POST['products'] to find the new checked ones and you need to loop through $already_selected to find the unchecked ones.
<?php
// Select from db or something
$already_selected = array(2,3);
foreach($_POST['products'] as $i) {
if(!in_array($i,$already_selected)){
$save_dbarray[$i] = 'checked_update';
}
}
foreach($already_selected as $j) {
if(!in_array($j,$_POST['products'])){
$save_dbarray[$j] = 'unchecked_update';
}
}
print_r($save_dbarray);
// Do db update and select again and update $already_selected to display the checked ones
?>
<form action="save.php" method="post">
<?php
for ($i=1;$i<10;$i++) {
$checked = in_array($i, $already_selected) ? 'checked' : '';
echo '<input type="checkbox" name="products[]" value="' . $i . '" ' . $checked . '> '. $i .'<br>';
}
?>
<input type="submit">
</form>

HTML multiple checkboxes with identical name= into PHP $_POST

So I have a 3rd party survey tool that generates html surveys, and for multi-select checkboxes in a given question, it will name them all the same:
<input type="checkbox" value="1" id="V25_1" name="V25">
<input type="checkbox" value="2" id="V25_2" name="V25">
Is there a way that all the selected values can be retrieved in PHP?
$_POST by default seems to simply store only the last selected value.
Your code should be approximately the following:
<select multiple="multiple">
<input type="checkbox" value="1" id="V25_1" name="V25[]">
<input type="checkbox" value="2" id="V25_2" name="V25[]">
</select>
V25[] means that you can get the value from an array. e.g. $_GET['V25'][0]
You could also specify an index if needed:
V25[1] or V25[a]
You could run something like this before the form submit:
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("id"));
});
or
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("name")+"[]");
});
It is possible to retrieve all variables when you have multiple elements with identical 'name' parameters.
After much scouring the internet for a solution, I wrote the following php script which grabs the raw post data, and parses it:
<?php
function RawPostToArray() {
$rawPostData = file_get_contents("php://input");
if($rawPostData) {
$rawPostData = explode('&', $rawPostData);
if($rawPostData && is_array($rawPostData) && count($rawPostData)) {
$result = array();
foreach($rawPostData as $entry) {
$thisArray = array();
$split = explode('=', urldecode($entry), 2);
$value = (count($split) == 2) ? $split[1] : '';
if(array_key_exists($split[0], $result)) {
if(is_array($result[$split[0]])) {
$result[$split[0]][] = $value;
}
else {
$thisArray[] = $result[$split[0]];
$thisArray[] = $value;
$result[$split[0]] = $thisArray;
}
}
else {
$result[$split[0]] = $split[1];
}
}
return $result;
}
else return array();
}
else return array();
}
?>
Any duplicate 'names' are bumped down into an array within the result, much the way $_POST does, when the HTML is coded correctly.
There is probably plenty of room for improvement here, and I'm sure not all situations are accounted for, but it works well for my application.
Suggestions are appreciated where improvements can be made.

Categories