How do I get information from an unknown number of checkboxes - php

On one of my html pages, I have loop that creates an n number of checkboxes (depends on how many entries there are in the database).
When the user presses the submit button, it opens up another html page, How do I set up my second page to receive all the ticked items. Note, the names of the checkboxes are also unknown, so far I have this on my first page:
<form action='tests.php' method='get'>
<p>
<?php
while ($row = mysql_fetch_array($result)) {
print "<tr><td><input type='checkbox' name=".$row{'Info'}." value=".$row{'Info'}.">".$row{'Info'}."<br></td></tr>";
}
?>
</p>
<input type="submit" value="Submit">
</form>
When tests.php is opened, how do I get all the check-marked values?
Reading form other posts, I believe I have to use an array to get the values, however, I still cannot see how to implement an array here.

Put them into an array:
HTML:
<form action='tests.php' method='get'>
<p>
<?php
while ($row = mysql_fetch_array($result)) {
print "<tr><td><input type='checkbox' name='checkbox[".$row{'Info'}."]' value=".$row{'Info'}.">".$row{'Info'}."<br></td></tr>";
}
?>
</p>
<input type="submit" value="Submit">
</form>
PHP:
$checkboxes = $_GET['checkbox']; // this is an array
foreach ($checkboxes as $key => $value) {
// $key is the value of $row{'Info'}
}
It should be noted that this will not work if your values have brackets in them unless you use urlencode() on them first.

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 store and re-use values of every printed element in a foreach construct PHP

I am currently writing a textbased game in php and i just encountered a complication that I really want to solve somehow. I tried to search for solutions but without any success. This is my problem:
Im using a foreach to print out all the items in an array where the element value is greater than 0 (i dont want to show the items the user have 0 of).
BUT i cant figure out how to make each and every number input window and submit button printed unique (together) so that when the player clicks "sell" its sells the right item and the right amount of it! Right now it seems like i can only access the amount of the last element that the player want to sell.
So my question is: How to store and re-use values of every printed element in a foreach construct?
Se below:
if (loggedIn()) { ?>
<h3><center>Your items</center></h3><hr><br />
<div class=tools>
<table class="inventory">
<?php
foreach (array_slice($items, 2) as $key => $value) {
if($value>0){
echo "<tr><form action='store.php' method='GET'>
<td>".$key."</td>
<td>".$value."</td>
<td>st</td>
<td><input type='number' name='".$key."' value='0'></td>
<td><input type='submit' value='sell'></td>
</form></tr>";
}
}
if(isset($_GET['Sell'])){
echo $_GET[$key];
// Here i want to decrease the value of given $key
}
?>
</table>
</div>
<?php
}else {
header('Location: index.php');
}
One way to do this is put one form around your table, and use a button element to indicate which item is being sold. All of the text inputs will be submitted, but only the button that was clicked will be submitted, so you can use the value of that button to get the correct text input. Like this:
<form action='store.php' method='GET'>
<table class="inventory">
<?php
foreach (array_slice($items, 2) as $key => $value) {
if ($value > 0) {
echo "<tr>
<td>$key</td>
<td>$value</td>
<td>st</td>
<td><input type='number' name='items[$key]' value='0'></td>
<td><button type='submit' name='item' value='$key'>sell</button></td>
</tr>";
}
}
?>
</table>
</form>
Then you can get the item sold (which button was clicked):
$item_sold = $_GET['item'];
and use that to get the quantity
$number_sold = $_GET['items'][$item_sold];
I would recommend using POST rather than GET for this, since I assume it will make a change on your server.

How to get access to dynamically generated radio buttons using POST

I have some dynamically generated HTML radio buttons based on fetching each character from a database table as show below:
<form name="form" id="myForm" method="POST" action="process.php">
<?php
$stmt = $this->registry->db->getDB()->prepare("SELECT * FROM characters");
$stmt->execute();
if($stmt->rowCount() > 0)
{
foreach($stmt as $row)
{
?>
<input type="radio" name="<?php print $row[0];?>" value="<?php print "value" . $row[1];?>">
<?php
}
}
?>
</form>
How would I get access to each selected radio button that is generated in my PHP script using $_POST[], because the name attribute of each radio button is created dynamically, I can't get my head around how I would access each radio button value in PHP so I can process the form.
Note that each radio button generated will be unique so they will not be grouped with the same name.
One easy way would be to create an array, in this case data[]:
<input type="radio" name="data[<?php print $row[0];?>]" value="<?php print $row[1];?>">
Then to get them:
if(isset($_POST['data'])) {
foreach($_POST['data'] as $name => $value) {
echo "$name = $value<br/>";
}
}

How can I collect checked items from PHP array served in form?

I have a form which builds the form items from a foreach loop and puts a checkbox by each item:
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu" value="no" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
As you can see, I start with each item unchecked. What I would like to know is how I should build the nextStep.php script to create individual php variables that I can echo on the nextStep.php page after the user clicks the submit button?
You must identify that this input is an array of values, by appending [] on the name:
echo '<input ... name="reveal_menu[]" ...>';
In nextStep.php:
foreach($_POST['reveal_menu'] as $checkbox)
echo $checkbox;
EDIT to answer OP comment:
You would need to create an array to handle these values. But $_POST['reveal_menu'] itself is an array. So can access $_POST['reveal_menu'][0], for example.
Keep in mind that $_POST['reveal_menu'] is an array with checked values ONLY . The index 0 doesn't point for the first checkbox of your form, but for the first checkbox checked from your form.
Each item needs to have a unique value, probably the menuname, so you can tell which ones are checked, and the name needs to have [] operator appended to the end.
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu[]" value="$menuname" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
When you loop through, you'll get an array of values.
<?php
foreach($_POST['menuname'] as $v)
{
echo($v . 'Was checked.');
}
?>

how do I use value of input element in a new file (GET method)

<?php
// code that connects to database
?>
<table>
<form method="get" action="processorder.php">
<?php
while (list($pizzaId, $pizzaName, $pizzaNumber, $pizzaPrice) = mysql_fetch_row($resultaat))
{
echo "<tr>
<td>".$pizzaName."</td>
<td>".$pizzaNumber."</td>
<td>".$pizzaPrice."</td>
<td> <input type='text' name='$pizzaId' value='$qty' size='3' /></td>
</tr>";
}
mysql_close($db);
?>
<input type="submit" value="Order now" />
I would like to display the pizzas of where there is a value in the input element.
the processorder.php file would look like:
my url shows the pizzaId's with the values after the '='. So I figured I have an associative array on my hands.
I thought I'd put a foreach loop in my processorder.php going like
foreach ($_GET['pizzaId'] as $pizza => $qty)
{
echo $pizza." ".$qty."<br />";
}
Yet, when I use the foreach loop, the error in my browser says that the argument of my foreach loop is invalid because $_GET['pizzaId'] isn't an array to begin with (I checked with is_array).
So how do I get access to those values in my value attribute of the input element?
Your $pizzaId is an integer.
I would change the name of the input elements to name="pizzas[$pizzaId]", and then you could access it through PHP like this:
foreach ($_GET["pizzas"] as $pizzaId => $pizzaQty) {
echo "$pizzaId $pizzaQty<br />";
}
with this method, instead of just plain name="pizzas[]", you also retain the association with the actual pizzaId.
If you need to put an array into $_GET then your url should look like:
//site/page?pizzaID[]=123&pizzaID[]=124
You can achive this with similar usage of name of input field
<input name="pizzaID[]" />
<input name="pizzaID[]" />

Categories