form checkbox group in php - php

im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}

It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}

You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>

Related

Form with checkboxes getting all checked checkboxes

I am trying to make a random tournament generator, where I can select names from a list with checkboxes and then randominze them into a different order.
I have the following form:
<form method="post" action="<?php echo ROOT ?>HomeController/createTournament/" enctype="multipart/form-data">
<div class="form-group">
<label for="participants">Select participants</label><br>
<?php foreach($players as $p): ?>
<input type="checkbox" name="participants" value="<?php echo $p['name'];?>"> <?php echo $p['name'];?><br>
<?php endforeach; ?>
</div>
<button type="submit" class="btn btn-primary btn-block" name="create">Show participants</button>
</form>
This form show's a checkbox and behind the checkbox the name of the participant.
This is my method:
public function createTournament() {
if(isset($_POST["create"])) {
$participants = $_POST['participants'];
}
include('app/views/showTournament.php');
}
That means I am saving the checked ones into $participants, right?
In the file showTournament, I know have access to $partipants.
I try to var_dump $particpants and it shows me:
string(6) "Onlyoneselected name"
So I tried a foreach, to get ALL of the selected names.
<?php
foreach($participants as $p) {
echo $p;
}
;?>
The foreach isn't showing anything, but the file has access to $participants. I want all the names on my screen, so I can start randomizing them. What do I do wrong?
<input type="checkbox" name="participants"
This line here is the root of your problems.
Because every checkbox has the same name, the value of $_POST['participants'] gets overridden for each checkbox in the list.
If you change that snippet to:
<input type="checkbox" name="participants[]"
Then $_POST['participants'] becomes an array of all checked values.
You need multiple checkbox values.
And therefore, HTML name of the input should be multiple (array)
<input type="checkbox" name="participants" will return string, only latest submitted value.
<input type="checkbox" name="participants[]" will return array of all submitted values.
So, replacing name="participants" to name="participants[]" will work.

Rendering checkboxes from DB and then update the DB if modifyed

Thanks for coming!
So on the DB I have Table1 and Table 2, they have the same columns.
What I want to do is that an administrator check the changes requested on Table2 and with a checkbox for each column decide which ones are ok and which others aren't.
So far I have this
If there are changes between Original and Modified tables the cell turns its color to green and Autochecks itself...
So far so good, but.
If I press the Submit button I don't seem to catch the VALUE of the ticked checkbox, so far the maximum I accomplished to catch was a "ARRAY" value, literally, not the content but "ARRAY" just like that, the code of each cell is way to long, Right now I'm focusing on getting the first row right so i can implement that to the other ones, so here is what it looks like: (sorry for the awful mess it is)
<tr>
<td style="text-align: center">Codigo de Cliente</td>
<td style="text-align: center"><?php echo $row1['idClientes']; ?></td>
<td <?php if($row1['idClientes']===$row2['idClientes'])echo "bgcolor='green' ";?> style="text-align: right"><?php echo $row2['idClientes']; ?><input type="checkbox" name="checkbox[]" id="checkbox" value:"<?php echo $row2['idClientes']; ?>" <?php if($row1['idClientes']===$row2['idClientes'])echo "checked='checked' onclick='this.checked=!this.checked;' value:'".$row2['idClientes']."'";?> ></td>
</tr>
And here is the PHP
<?php if(isset($_POST['submit']))
{
$idClientes =$_POST['checkbox'];
echo "<script>
alert('$idClientes'),
</script> ";}
That echo/alert gives me 'Array' as a result when it should be '14359.
Any advice? Thanks in advance!
PD: If the solution excludes Jquery/Javascript that would be awesome, Im not familiar with those languages yet, so only php/mysql/html for now.
As noted by the comment(s), your form inputs have array names:
<input type="checkbox" name="checkbox[]" value="14359" />
<input type="checkbox" name="checkbox[]" value="2222222" />
<input type="checkbox" name="checkbox[]" value="dvdza#whatever.com" />
If a couple are checked, will produce an array like this:
Array
(
[checkbox] => Array
(
[0] => 14359
[1] => dvdza#whatever.com
)
)
If you want to retain the array names but be specific about labeling, you need to make the array associative:
<input type="checkbox" name="checkbox[idClientes]" value="14359" />
<input type="checkbox" name="checkbox[idSomethingElse]" value="2222222" />
<input type="checkbox" name="checkbox[email]" value="dvdza#whatever.com" />
When checked would give you:
Array
(
[checkbox] => Array
(
[idClientes] => 14359
[email] => dvdza#whatever.com
)
)
This way you can then do:
if(isset($_POST['checkbox']['idClientes']))
$idClientes = $_POST['checkbox']['idClientes'];
It seems like the Array you're getting back should contain all the values that are checked. It should actually help you complete the rest of the implementation of getting the values of the ticked checkboxes, by just indexing an element that you need or by looping through the array.

How do I post two uneven arrays where one set is checkboxes and the other text input boxes

I can't get this to work. I need to update many records in 1 column, based on what's checked and filled out. I tried different combinations of checking and unchecking and having the text fields blank or not blank, and in this php post code i tried many different things, but can't figure out the correct combinations and if/elses or issets or empties, etc.
the values in the checkboxes correspond to record/row IDs. all the text boxes will be prefilled with prices. all the checkboxes will be dynamically checked or unchecked. a person can undo checked checkboxes if they want or check checkboxes that are not checked. on post, all the records that are checked should get the matching text box value.
the problem is i can't get the 2 arrays to match in my post. for example, in this sample set of fields, let's say i check the 2nd checkbox and the 4th checkbox. the records that should update and the values that should save into the column should be as follows...
2 -> 17.67
4 -> 19.84
but instead i get:
2 -> 16.95
4 -> 17.67
or this (if i remove the values from 1st and 3rd text boxes):
2 -> empty
4 -> 17.67
or this (2nd checkbox id and value missing completely)
4 -> 17.67
what am i doing wrong?
if (isset($_POST["savelist"]) && !empty($_POST["savelist"])) {
$productidcheckboxes = isset($_POST['productid']) ? $_POST['productid'] : array();
$listprices = isset($_POST['listprice']) ? $_POST['listprice'] : array();
//other things i tried
//$listprices = (empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$listprices = (!empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$productidcheckboxes = $_POST['productid'];
//$listprices = $_POST['listprice'];
$new = array();
for ($i=0; $i<count($productidcheckboxes); $i++) {
$new[] = $productidcheckboxes[$i];
$new[] = $listprices[$i];
}
$k=0;
foreach ($new as $value) {
$k++;
if($k==1){
$theid = $value;
}
if($k==2){
$thelistprice = $value;
//different ifs i tried
//if ($theid<>"")
//if ($value<>"")
//if ($theid<>"" && $thelistprice<>"")
//if ($theid<>"" && $value<>"")
if ($thelistprice<>"")
{
echo $theid.": ";
echo $thelistprice."<br>";
//update table with the list prices
//mysql_query("UPDATE table_name SET mylistprices = '$thelistprice' WHERE id = $theid");
}
$theid = "";
$thelistprice = "";
$k=0;
}
}
}
form looks like this
<form action="" method="post">
<input type="checkbox" value="1" name="productid[]">
<input type="text" value="16.95" name="listprice[]">
<input type="checkbox" value="2" name="productid[]">
<input type="text" value="17.67" name="listprice[]">
<input type="checkbox" value="3" name="productid[]">
<input type="text" value="18.81" name="listprice[]">
<input type="checkbox" value="4" name="productid[]">
<input type="text" value="19.84" name="listprice[]">
<input type="checkbox" value="5" name="productid[]">
<input type="text" value="16.85" name="listprice[]">
<input type="submit" value="Save List" name="savelist">
</form>
by the way, by uneven i mean all the checkboxes will have values so correct rows will be updated, but the text boxes may or may not be filled. i would like it if i didn't have to clear any values in checkboxes or text inputs. it should just update records that are checked with it's corresponding values, and ignore non-checked checkboxes and the non-checked checkboxes corresponding values. but in the end, i may have to change how it's done, but i can't solve this one.
Add hardcoded numeric values to the form names so they match up in your processing page. Right now they are random:
<form action="" method="post">
<input type="checkbox" value="1" name="productid[1]">
<input type="text" value="16.95" name="listprice[1]">
<input type="checkbox" value="2" name="productid[2]">
<input type="text" value="17.67" name="listprice[2]">
<input type="checkbox" value="3" name="productid[3]">
<input type="text" value="18.81" name="listprice[3]">
<input type="checkbox" value="4" name="productid[4]">
<input type="text" value="19.84" name="listprice[4]">
<input type="checkbox" value="5" name="productid[5]">
<input type="text" value="16.85" name="listprice[5]">
<input type="submit" value="Save List" name="savelist">
</form>
Now you know if the user checks product[4], it really is product[4]. When you leave your keys blank like productid[], that is just an anonymous spot in the array and makes it impossible to track when dealing with checkboxes that have no value unless checked.
If you check off productid[2] and productid[4] you know that the values in the listprice array are the values that go with what you have checked off:
Array
(
[listprice] => Array
(
[1] => 16.95
[2] => 17.67
[3] => 18.81
[4] => 19.84
[5] => 16.85
)
[productid] => Array
(
[2] => 2
[4] => 4
)
)
To access the values, loop through the productid but access the listprice:
foreach($_POST['productid'] as $key => $value){
echo $_POST['listprice'][$value].'<br />';
}

checkboxes in php form doesn't work

How can I use the conditional OR in a form with isset?
I have this but it does not work.
FORM HTML:
...
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
...
and the PHP
$cargas=array($_POST['carga1'],$_POST['carga2'],$_POST['carga3'],
$_POST['carga4'],$_POST['carga5'],$_POST['carga6'],
$_POST['carga7'],$_POST['carga8'],$_POST['carga9'],
$_POST['carga10'],$_POST['carga11'],$_POST['carga12'],
$_POST['carga13'],$_POST['carga14'],$_POST['carga15'],
$_POST['carga16'],$_POST['carga17'],$_POST['carga18']);
if(isset($cargas[0]) ││ isset ($cargas[1])){
$cargas[0]=5.62;
$cargas[1]=4.5;
echo "$cargas[0]<br>";
echo "$cargas[1]<br>";
}
i expect that this works but is not.
Only checked checkbox is posted to the server.You have to change your condition using pregmatch and work accordingly.
$postData = $_POST;
foreach ($postData as $key => $value) {
$match = preg_match('|cargas(\d+)|', $key, $matches);
if ($match) {
$index = $matches[1];
if($index == 0 || $index == 1){
// do your stuff which you would have done in case of $cargas[0] ,$cargas[1]
}
}
}
I think array is not Suitable way to do this try following
try this
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
.....................................
<input type="submit" name="submit">
<?php
if(isset($_POST['submit'])){
//
$category1=$_POST['carga1'];
$category2=$_POST['carga2'];
$category3=$_POST['carga3'];
if(isset($category1) ││ isset ($category2)){
$category1=5.62;
$category2=4.5;
echo "$category1<br>";
echo "$category2<br>";
}
}
?>
only the checked checkboxes get posted. so it needs slightly different appraoch.
You can acheive it like this-
put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' id='testName' value='0' name='carga1'>
<input type='checkbox' id='testNameHidden' value='1' name='carga1'>
</form>
Before submitting the form , disabled the hidden field based on the checked condition.
<script>
if(document.getElementById("testName").checked){
document.getElementById('testNameHidden').disabled = true;
}
</script>
I personally think its the easiest approach for this.
ok, check boxes in html works as follows,
<input type="checkbox" name="carga1" value="1">
<input type="checkbox" name="carga2" value="123">
in php,
if the check box is in checked state during the submission, you will get
isset($_POST['carga1']) as true, else the form element would not be available in post data, hence false.
and in cheked state you will get value for
$_POST['carga1'] as 1 and
$_POST['carga2'] as 123
and if you want to group the check boxes in form you can use a single name for multiple check boxes and different values,
<input type="checkbox" name="carga[]" value="1">
<input type="checkbox" name="carga[]" value="2">
<input type="checkbox" name="carga[]" value="3">
<input type="checkbox" name="carga[]" value="4">
and in php you will get an array of selected values of the check boxes
$arr=$_POST['carga'];
and you can use foreach to iterate through the values,,,

set two values for an input name attribute

i have a check box list that some limited check boxes can be selected. for this i set the name attr of all them "answer" to work with the js function properly(i got the function from some where).
<?php
else if($result['type'] == "multipleChoice"){
echo'
<div><input type="checkbox" name="answer ans1" value="'.$res['probAns1'].'"/><input type="text" class="prob-ans" name="prob-ans1" value="'.$res['probAns1'].'"/><lable>:گزینه 1</lable></div>
<div><input type="checkbox" name="answer ans2" value="'.$res['probAns2'].'"/><input type="text" class="prob-ans" name="prob-ans2" value="'.$res['probAns2'].'"/><lable>:گزینه 2</lable></div>
<div><input type="checkbox" name="answer ans3" value="'.$res['probAns3'].'"/><input type="text" class="prob-ans" name="prob-ans3" value="'.$res['probAns3'].'"/><lable>:گزینه 3</lable></div>
<div><input type="checkbox" name="answer ans4" value="'.$res['probAns4'].'"/><input type="text" class="prob-ans" name="prob-ans4" value="'.$res['probAns4'].'"/><lable>:گزینه 4</lable></div>
';
?>
first is it correct to set two value for name attr. i did it but didnt work. like it isnt acceptable the second value.
if not how can i specify them if i have just name="answer"? i want to set some values in php if one of these check boxes is set.
<?php
if($result['type'] == "multipleChoice"){
$question->probAns1 = mysql_real_escape_string($_POST['prob-ans1']);
$question->probAns2 = mysql_real_escape_string($_POST['prob-ans2']);
$question->probAns3 = mysql_real_escape_string($_POST['prob-ans3']);
$question->probAns4 = mysql_real_escape_string($_POST['prob-ans4']);
if(isset($_POST['ans1'])){
$question->answer1 = $_POST['prob-ans1'];
}
}
?>
No, you can't have two names like you did. Following however is possible:
<input type="checkbox" name="answer[]" value="abc" />
<input type="checkbox" name="answer[]" value="def" />
Your $_POST will look like following (if both are checked):
array(
'answer' => array(
0 => 'abc',
1 => 'def'
)
)
You can also specify the array-keys, thus name="answer[answ1]" value="abc" will give you $_POST['answer']['answ1'] == 'abc'
Here is link of what you need to do.
In one sentence, you need to use arrays of html elements.

Categories