How to retrieve the Selected checkbox names ( Multiple Selected) in PHP? - php

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>";
}

Related

How to make a hidden checkbox in php?

I've got a set of checkboxes but one shuld be always checked, I want that this checkbox is also hidden from my page, I need this beacause I have the DB that can be read only if this attribute is checked..
Please I need answers where you teach me how to hide the checkbox and NOT where you say that I can change the comand on SQL
$sqlPers= "SELECT * FROM personalizzazione";
$countPers = 0;
foreach ($dbh->query($sqlPers) as $rowPers){
$selez = '';
if($rowPers['Condimento'] == 'Base')
$selez = " checked = 'checked' ";
echo "<div class='checkbox'><label class='bianco'><input type='checkbox'" .
$selez . "name='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"].
"' id='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"]."'>".
$rowPers['Condimento']." (€ ".$rowPers['Prezzo'].")</label></div>";
$countPers++;
}
I tried to add type = 'hidden' in the variable $selez but nothing
Otherwise can someone say me how to disable it or hide it throught ccs?
I've tried searching on internet and there weren't full solutions for my question
There are two things you can do:
Method 1 - Hide it using CSS:
<input type='checkbox' style='display:none;'>
Method 2 - Use a hidden type instead of checkbox:
Another option would not have a checkbox, but rather have a separate hidden input tag.
<input type='hidden' name='pizza' value='value'>
You can hide it with style="display:none;"
But since it is hidden, does it have to be a checkbox?
A regular hidden input would do the job, too.
Look at the HTML that gets sent to the browser: You have already set type='checkbox' in your string, so having an additional type='hidden' may not give you what you want. You end up with <input type='checkbox' type='hidden'...
Your error was tough to see because you're writing your code in a way that is really difficult to debug. It's better practice to do all the logic up front. You're better off building all the attributes in code first. For example:
//run test to make $hide true for the loop where you want to hide the checkbox
$type = 'checkbox';
$style = $hide? "display:none" : "";
$name = $id = "$rowPizza[idPizze]_$rowPers[idPersonalizzazione]";
...
//then later when you can build your html
$html = "<div class='checkbox'><label class='bianco'><input type='$type' name='$name' id='$id' style='$style'>";
//Finally once you've built the whole html you can echo it
echo $html;
Note that we set display:none style when the $hide variable is true. Otherwise, the style will just be an empty string and the checkbox will be shown

How to access checkboxes with unknown names in PHP

I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.

php sum values of form check boxes when checked

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.

counting number of checkboxes check in email

Here is my php code:
$tasks = ' ';
$help = $_POST['help'];
if(empty($help))
{
$tasks = "None selected.";
}
else
{
$N = count($help);
$tasks = $N;
}
And the HTML is:
<input type="checkbox" name="help" value="sign"> //with several inputs with different values
On the form submit, it emails and outputs everything appropriately except the count of the array. It outputs the $tasks variable at the end of the email always as 1, except when no check boxes are selected. Any combination of selecting checkboxes (1-6) ends up with an array of 1 length. Anyone know why? Thanks!
You'll need to make the checkboxes an array. Change the name to:
<input type="checkbox" name="help[]" value="sign">
You should change your HTML code to:
<input type="checkbox" name="help[]" value="sign">
so that help will be an array. If you only use help, $_POST['help'] will only contain the last value.
you have to rename fields name="help[]" so it can be parsed as array.

Render HTML checkbox inputs based on MySQL data

I have this table contains name and value, how can i convert the contents of
$row=mysql_fetch_array($result);
into checkboxes?
Assuming $row is an associative array mapping column name onto a boolean 1 or 0 value, you could do something like this:
foreach($row as $colname=>$boolean)
{
//create a name for the checkbox which will produce a nice
//PHP array of checked column names in $_POST['col']
$name="col[$colname]";
//create an id for the checkbox
$id='col'.$colname;
//now we output the checkbox - on form submission you will
//see an element in $_POST['col'][$colname] if checked, and
//no element at all if unchecked...
echo '<input type="checkbox" value="1" '.
'name="'.$name.'" id="'.$id.'" '.
($boolean?'checked="checked"':'').
'>';
//output a label - note we'd tied this to the id of the checkbox
//which means you can click the label to tick the box
echo "<label for=\"$id\">colname</label><br/>";
}
When the form is submitted, you'll get an array in $_POST['col'] indexed by column name, but only for those boxes which are checked, so you'd set to false any columns which are not set.
See here: http://dev.w3.org/html5/spec/Overview.html#checkbox-state
So, try this:
<input type="checkbox" checked="true">

Categories