I have a form in php that displays checkboxes. These checkboxes are associated with a numerical value populated from mysql. What I'm looking to do is add the values of each checkbox, but only if the box is checked.
The problem I am running into is no matter which boxes I have checked, the value from the first checkbox(es) are returned. For example, if there are 5 total checkboxes and I select the bottom 2, the returned sum is for the 2 top boxes not the bottom boxes. It seems my php code knows boxes are being checked, but just doesn't know which boxes are being checked.
Here is my form code
echo "<input type=\"hidden\" name=\"ID[]\" value=\"".$row['ID']."\" />";
echo "<tr><td> <input type=\"checkbox\" name=\"checked[]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[]\" value=\"".$row['amount']."\" />";
and here is my post
if('POST' == $_SERVER['REQUEST_METHOD']) {
$amt = 0;
$totamt = 0;
foreach($_POST['ID'] as $i => $id)
{
$id = mysql_real_escape_string($id);
$checked = mysql_real_escape_string($_POST['checked'][$i]);
$amt = mysql_real_escape_string($_POST['amount'][$i]);
if ($checked == "Y") {
$totamt = $totamt + $amt;
$amt = 0;
}
}
echo $totamt;
}
Thank you for your help.
The only checkboxes that are sent from the form are the ones that are checked, and the array indexes will start from 0 no matter which ones they are. So there's no correspondence between the indexes of the checkboxes and the indexes of the hidden fields. There are a few ways to deal with this.
One way is to put explicit indexes in the checkbox names:
echo "<tr><td> <input type=\"checkbox\" name=\"checked[".$row['ID']."]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[".$row['ID']."]\" value=\"".$row['amount']."\" />";
Then you can add up:
$totamt += $_POST['amount'][$_POST['checked'][$i]];
Another way is to put the amounts directly in the value of the checkboxes, instead of the useless Y value:
echo "<tr><td> <input type=\"checkbox\" name=\"checked[]\" value=\"".$row['amount']."\" /></td>";
Then you do:
$totamt += $_POST['checked'][$i];
A third way is to put explicit indexes in the names of all the fields, instead of letting PHP assign them when the form is submitted:
echo "<input type=\"hidden\" name=\"ID[".$i."]\" value=\"".$row['ID']."\" />";
echo "<tr><td> <input type=\"checkbox\" name=\"checked[".$i."]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[".$i."]\" value=\"".$row['amount']."\" />";
where $i is a variable that you increment as you're generating the form. This will make the indexes work the way your form code expects.
Looks like your hidden field and the actual checkbox have different names try putting them the same name
<input type='hidden" name='checkbox" value="no" />
<input type="checkbox" name="checkbox" value=$row['ID'] />
That way when you check the $_POST for checkbox name it will either show no or the id and you can determine what was checked
Basically the name of the hidden and checkbox should be the same
Another option to the ones already mentioned would to use JavaScript to do your adding and store the result in a hidden input field. You could use the onclick even to run a JS function that would add up the values (and you should definitely set it in the value of the checkbox instead of a hidden field). Then store your total into the hidden input field value. This would get passed in your POST along with the checkboxes. If you wanted to double check the amount, you could sum up the values of the checkboxes & compare to the hidden field.
Related
I have two checkbox forms on the same page. When they are both there, the second form will not work. I'm wondering if there is a way to have both on the same page with them both needing the $index of the input.
The input fields are similar to this (the other is unchecked):
echo "<input type='checkbox' name='check[]' value='$index' onChange='this.form.submit()' checked='checked'>";
echo "<input type='hidden' name='itemDELETE$index' value='$bookID'>";
This is the other
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='itemADD$index' value='$bookID'>";
And the data is stored like:
$value = $_POST["check"][0];
$toDELETE = $_POST["itemDELETE" . $value];
and
$value = $_POST["checkbox"][0];
$toADD = $_POST["itemADD" . $value];
I have tried renaming $value but the issue lies in the $index on the input fields.
They are outputting correctly, but the second one will not store the value properly in it's variable, whereas the first does. The second is the delete one.
When I remove the first forms functionality, the second form works. But when I add it back, the second one stops working. Not picking up on the itemDELETE $value
If I manually put the value in like this "itemDELETE0" instead of ["itemDELETE" . $value]it works. But I need the $value to picked up on since it's a foreach loop.
My solution to this was to put the second form in different shortcode, and include it on the page. It works well and doesn't clash. Same code, just in a different shortcode.
Then on the page created, I used the shortcode for the first form and then put the shortcode for the second form below it.
And instead of defaulting it to checked, I had to use it unchecked. But that works alright.
I'm trying to write an attendance system that, when a user is present at a class, the staff will check a box and the program will then add one to the present count of the relevant customers. The problem is to output the register, taken from phpMyAdmin, it uses a while loop so all the checkboxes have the same variable name. This is the code I have so far...
echo "<form 'action=badminreg.inc.php' method='post'>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row['bookingID']."</td><td>".$row['firstName']."</td><td>".$row['surname']."</td><td><input type='checkbox' name='present' value='present'</td><td><input type='checkbox' name='incident' value='incident'</td></tr>";
}
echo "<input type='submit' name='reg-submit'>";
echo "</form>";
isset($_POST['reg-submit']);
$pres = $_POST['present'];
I need to separate the check box inputs so that the program will be able to mark individual users differently to others. I'm sort of new to PHP as this is for my A-level coursework so is there a way to get around this? Any help would be great. Thanks
You can define the name for the checkbox elements as array and pass the bookingID as value.
Example (untested):
$output = "<tr><td>{$row['bookingID']}</td><td>{$row['firstName']}</td><td>{$row['surname']}</td><td><input type='checkbox' name='present[]' value='{$row['bookingID']}'</td><td><input type='checkbox' name='incident[]' value='{$row['bookingID']}'</td></tr>";
The variables $_POST['present'] and $_POST['incident'] contains then an array with the IDs of the selected check boxes.
If you change it to name='present[]' then when you submit the data again, you'll get an array of values inside $_POST["present"] instead of a single one. (You'll get one item in the array for each checkbox with that name which was actually checked - a quirk of HTML forms is that if the checkbox wasn't checked, its value is not submitted at all).
You'll also want to change the value of the checkbox to be the ID of the customer (or booking, maybe), so you can identify which box was checked.
Same for the "incident" checkbox as well, of course.
So you're aiming for something like this, I think:
echo "<tr>
<td>".$row['bookingID']."</td>
<td>".$row['firstName']."</td>
<td>".$row['surname']."</td>
<td><input type='checkbox' name='present[]' value='".$row['bookingID']."'</td>
<td><input type='checkbox' name='incident[]' value='".$row['bookingID']."'</td>
</tr>";
I've created a php page which retrieves question and options(as MCQ's) from the database and in that Radio buttons are created dynamically using echo()The name for each radio button group is assigned into an array from which one by one index's value is set to the name attribute.Example:
$result=mysqli_query($db,$sql);
$numrows=mysqli_num_rows($result);//gets the number of questions
$radiogrp_name=array();
for($i=0;$i<$numrows;$i++){ //creating array of names for each set of radio buttons
$radiogrp_name[$i]="q".$i;
}
$i=0;
while(($myrow=mysqli_fetch_array($result)) && ($i<$numrows)){
echo $myrow["q_no"].". ";
echo $myrow["ques"]."<br><br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='a'/>".$myrow["A"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='b'/>".$myrow["B"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='c'/>".$myrow["C"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='d'/>".$myrow["D"]."<br><br><br>";
$i++;
}
How would I get the selected radio buttons and set them into a SESSION variable? Can anyone help with this? Or any other way to implement this?Thank you in advance!
On the page that the form is POST'ed to you are going to need to look through the $_POST array and strip out the relevant answers. Ideally you would have a list of expected indexes to drive that page, but if not you could just try to pattern match the indexes.
Something like:
$results = array();
foreach($_POST as $key => $value){
if(preg_match("/q(\d{1,3})/", $key, $matches)){
$results[$matches[1]] = $value;
}
}
results would then contain an array of values indexed by the numeral in name="q#" and you would just set it to the session or do with it whatever you need.
EDIT
by the way, you'll need to wrap your string inclusion in curlies since it is an array.
echo "<input type='radio' name='{$radiogrp_name[$i]}' value='d'/>"
I have been trying to make a system for my school and some of the code is giving me a problem. i have a teachers page on which i input some details from a database and give a radiobutton with each record. when the user clicks submit it is supposed to go to a different page and put only the records into a differnt table for which the radiobutton was checked.
The code for making the radiobutton is
while($row=mysql_fetch_array($sqlquery))
{
echo "<tr> <td>$row[Name]</td><td> $row[Number]</td><td>$row[Form]</td><td> $row[Outings_left]</td><td>$row[Night_outings_left]</td> <td><input type='radio' id='$c' name=' $c' value='checked' /></td><td><input type='date' id='$sd' name='$sd' /></td><td><input type='date' id=' $ed ' name=' $ed' /></td></tr>";
$arr= Array($n=> Array(1=>'row[name]', 2=> 'row[number]') );
$c++;
$sd++;
$ed++;
}
Note- there are also two date fields getting the values in a similar manner
on the other page i am trying to check whether the radiobutton is checked in teh following manner. but this is showing that all the radoibuttons are unchecked
$cb1=$_POST['$c'];
echo $cb1;
if($cb1=='checked')
{
echo "entered";
}
EDIT: Also, does every variable start at 1? If so, $c = $sd = $ed. So you are having multiple radio inputs with the same id and name.
I had multiple checkbox which is generated using loop. After submitting the form I want to get the names of the selected individual checkbox to store it in database as id. Please help me.. Thanks in advance
Code i used for generating checkbox in loop:
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea[] \" />$strB</input></div>";
}
This code I used for getting names for it didnt worked. It only returned state of check box as ON
while (list ($key,$val) = #each ($box))
{
$aid=$val;
echo $aid;
}
If the set of checkboxes is marked up as so
<input type="checkbox" name="food[]" value="Cheese">
<input type="checkbox" name="food[]" value="Ham">
Then any checked values are accessed as an array from $_POST['food']
Obviously with a code example, as #rajasekar points out, it would be easier to recommend an approach
The id for each element is optional, but should/must be unique.
Form elements must have a name attribute, or they will not be submitted (use "covarea[]" for the name for all the chexboxes.
Checkboxes must have a value attribute, or they will be submitted with value "on".
You must ensure that $strA and $strB do not have HTML meta characters or your generated HTML will be invalid.
Your example had a space after the "[]" in the id, btw.
Perhaps like this.
$n = 0;
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
$n++;
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea${n}\" name=\"covarea[]\" value=\"${strA}\"/>$strB</input></div>";
}