Form with checkboxes getting all checked checkboxes - php

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.

Related

How can I display a variable number of items using radio buttons in HTML?

file.json: {"items":[{"num":1,"color":"red"},{"num":2,"color":"blue"}]}
Objective: Read file.json using PHP and delete the objects from the array and save.
Method: I am reading the file and displaying the array items alongside radio buttons. Objects corresponding to the selected radio button are deleted.
Code:
<?php
$myfile = fopen("/home/user/php/".$filename,"r" ) or die("unable to open file");
$myjsonstr = fread($myfile, filesize("/home/user/php/".$filename));
fclose($myfile);
$jsons = json_decode($myjsonstr, true);
?>
<form action="delete.php" method="POST">
<input type="radio" name="testcase" value="1"> <?php print_r($jsons["testcases"][0]);?>
<input type="radio" name="testcase" value="2"> <?php print_r($jsons["testcases"][1]);?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
Problem: I need to make my list dynamic in length because the value field of "items" can have variable number of objects. But it seems like number of radio buttons in HTML cannot be variable. As you can see from the code snippet, The no. of radio buttons is always 2. I'll have to change the code if the array in my JSON had 3 objects instead of 2.
Is it possible? How?
Thanks, prime_mover! That additional detail helps. Let's assume the part down to the json_decode is right, and you've got a decoded object in the variable $jsons.
Let's put the test cases in their own variable for brevity as well.
<?php
$testCases = $jsons["testcases"]; // array of indeterminate length
?>
<form action="delete.php" method="POST">
<?php
foreach ($testCases as $ix => $caseTxt) {
$v = $ix+1;
?>
<input type="checkbox" name="testcase" value="<?=$v;?>" /><?php print_r($caseTxt); echo "<br>"; ?><br>
<?php } ?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
The loop writes one new input for each entry in the $testCases array.
Not saying this is perfect code, or that it does exactly what you want to do, but it does handle a list of unknown length.
You would probably want to handle a zero length differently.
Notice I changed the type to checkbox, because your text below said "Delete Selected Values" so I guess you want to allow more than one to be selected.

How to get value of button inside the foreach loop using post method

Objective: Get the value of buttons from $_POST method, inside foreach loop
$projects= 'Project1, Project2, Project3'//from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button.
Displaying all the project names on buttons.
<?php foreach ($projectNames as $val):?>
<form action="projectSelected.php" method="post" id="project">
<button style="float:left" class="btn-default" value=""> <?php echo $val;?> </button>
Problem statement: When user clicks on button 'Project1', program should be able to get the value of button with $_POST['projectSelected'].
Help would be appreciated.
Set the value in hidden, and then post the value
<form action="projectSelected.php" method="post" id="project">
<input type="hidden" value="<?php echo $val ?>">
<input type="submit">
1) change the name of your variables :
$Projects => $projects (PHP convention)
2) add a trim after your explode function
$projectNames = array_map('trim', $projectNames);
3) use input submit instead of buttons (similar question)
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
Complete example:
$projects = 'Project1, Project2, Project3'; //from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button
$projectNames = array_map('trim', $projectNames);
Loop:
<form action="projectSelected.php" method="POST" id="project">
<?php foreach ($projectNames as $val) : ?>
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
<?php endforeach ?>
</form>
DO this:
<button style="float:left" name = 'projectSelected' class="btn-default"
value=""> <?php echo $val;?> </button>
what ever you set the name of button will becomes the key of $_POST array

Returning only the last value of query

This is my second code but the problem is I have 3 queries. So it only returns the last product_id when i Click update it always return product_id=3, but i want update the product_id=2
<form action="update_qty.php" method="POST">
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
<?php } ?>
</form>
Your problem is that the PHP is server side and you need something client side to read the value of the text box. You would need a page refresh to pass the text field value to the server so it could write it to the url in the anchor tag. Which is what the form submit would do, but as it would have submitted the value already the anchor tag would be pointless
To do it without a page refresh use Javascript. It would be easy to do with jQuery. You could add an event that writes whatever is entered in the text box the the anchor tags href as it is typed.
I'll do something more like this.
One form per product.In your case when you submit the form the qty value will always be the las found.
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<form action="update_qty.php" method="POST">
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
</form>
<?php } ?>
You can add more information like this
update
You can not get all values as like that because input name overwrite in every loop iteration.
For multiple values you can try in two ways like:
<?php
while($getorder = mysqli_fetch_array($order)){
$newArr[] = $getorder['price']."~".$getorder['product_id']."~". $ getorder['qty'];
} //while end
?>
<input type="hidden" name="allinputs" value="<?=$newArr?>">
Input field outside the loop.
In php explode array value with ~ and get the all values.
Other solution is that
Your input field name must be change like:
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price_<?=$getorder['product_id']?>">
<?php } ?>
Change field name in every iteration.
In current scenario either you need three different buttons or the best solution to use AJAX request .
update
On update_qty.php u can use like this
<?php echo $_GET['product_id'];?>

how to get value of checked with checkbox row in php?

I am trying to get values of rows which are checked using checkbox. So when I submit the form I want values of selected rows but I am not able to figure it out how to get it. Can anybody help me or guide me?
<?php
if(isset($_POST['invite'])){
// what should I write here to get value of hidden fields name and email which was selected
}
?>
<!doctype>
<html><head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
// performing select all /deselect all checkbox operation
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head><body>
<div class = 'middle' style = 'width : 700px;background-color:beige'>
// creating grid view
<form type="post" name ="contacts">
<span><input type="checkbox" id="selectall"/></span>
<div class = 'middle row'>NAME</div>
<div class = 'middle row'>E-MAIL</div>
<div class='line'></div>
<div class='line'></div>
<?php foreach($email as $e){
echo "<div>
<span><input type='checkbox' class='case' name='case'/></span>
<div class='row'>".$e['name']."
<input name='cname[]' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail[]' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
}
echo"<input type='submit' name='invite' value='invite'>
</form></div></body></html>";
}?>
After submitting the form, the value of a checked checkbox appears in the $_POST array like any other form fields. In your case, you have multiple checkboxes named case. None of those has a specific value assigned, so $_POST['case'] will equal on if any checkbox is checked, so this won't help you at all.
Change the name of the checkbox to case[] and assign a unique value to each, and $_POST['case'] will contain an array of the values of all checked checkboxes after submit. For instance, you could repeat the values of the hidden fields in the value attribute of your checkbox.
I wrote a small php script that should help you to understand, how checkboxes work with php. Just run it, play with the checkboxes and have a look at the $_POST array afterwards.
<!doctype html>
<html>
<body>
<form method="post">
<input type="checkbox" name="test[]" value="0"/>
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
<input type="checkbox" name="test[]" value="4"/>
<input type="submit"/>
</form>
<pre><?php var_dump($_POST); ?></pre>
</body>
</html>
If you want to keep your hidden fields and don't want to repeat their values in the checkbox element, you can also use the array key of their arrays as checkbox value:
<?php
$i = 0;
foreach($email as $e) {
echo "<div>
<span><input type='checkbox' class='case' name='case[]' value='".$i."'/></span>
<div class='row'>".$e['name']."
<input name='cname['".$i."']' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail['".$i."']' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
$i++;
}
Now, if $_POST['case']contains the values 2, 4 and 8 for instance, the emails you are looking for, are in $_POST['cemail'][2], $_POST['cemail'][4] and $_POST['cemail'][8]. Same applies for $_POST['cname'], of course.
First of all, there's a mistake in an argument of form tag:
<form type="post"
This should read
<form method="post"
Then, since you store name and e-mail in the inputs named cname[] and cemail[], they will be passed respectively in $_POST['cname'] and $_POST['cemail'] variables. Note that you named them in a way they will be passed as arrays, so actually, $_POST['cname'] is an array - it contains a key-value pair of 0 and the value attribute of the input control. So actually, your name and e-mail will be in $_POST['cname'][0] and $_POST['cemail'][0] variables.
Please analyse and also read Dealing with Forms section of PHP manual.

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories