How to submit multiple array checkbox with html forms - php

I am trying to submit multiple arrays with a checkbox form but I am only able to submit one array at the moment, here is what I have so far
In this example I am submitting an array of numbers with the delete[] array, this array gets processed properly, I also want to submit the array condition[] this does not get processed properly, what is the best way to solve this issue?
php code
$catalog = $database->getInventory();
if($catalog){
$numRows = sizeof($catalog);//count
echo "<b>Book Count:</b> ".$numRows."<br>";
echo "<form method='post' action='inventory.php'>";
echo "<table id='example' class='tablesorter' border='0' cellpadding='0' cellspacing='1'>";
echo "
<thead>
<tr>
<th>ISBN</th>
<th>Title </th>
<th>Rank </th>
<th>Condition </th>
<th><input type='checkbox' name='delete' value='all' /></th>
</tr>
</thead>\n";
foreach($catalog as $elem){
echo "
<tr>
<td>".$elem["isbn"]."</td>
<td>".$elem["title"]."</td>
<td>".$elem["rank"]."</td>
<td>".$elem["condition"]."</td>
<td>
<input type='checkbox' name='add[]'
value='".$elem['isbn']."_".$elem['condition']."_"."' />
</td>
</tr>";
}
echo "</table>";
echo "</form>";
}
example html markup
<form method='post' action='inventory.php'>
<table>
<tr>
<td>
<input type='hidden' name='addInventoryBook' value='1'>
<input type='submit' value='Add' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100001_used' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100001_new' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100003_new' />
</td>
</tr>
</table>
</form>
php function
function Inventory(){
if(isset($_POST['addInventoryBook'])){
if(isset($_POST['add']) && is_array($_POST['add'])){
$arr = array();
foreach($_POST['add'] as $checkbox){
$temp = explode("_", $checkbox);
$arr[] = array(
"isbn" => $temp[0],
"condition" => $temp[1],
"sub_condition" => $temp[2]
);
}
$this->addInventoryBook($arr);
}
else{
echo "No values have been set";
}
}
function addInventoryBook($arr){
foreach($arr as $elem){
//if used get sub-category
if($elem['condition']=='used'){
echo $elem['isbn']."-".ucfirst($elem['condition'])
.ucfirst($elem['sub_condition'])."<br>";
}
else if($elem['condition']=='new'){
echo $elem['isbn']."-".ucfirst($elem['condition'])."<br>";
}
}
}
All I want is to basically be able to pass two arrays to my php script
current output
100001
100002
100003
desired output
100001 good
100002 new
100003 new

The problem that you are having, I suspect, is that only the checkboxes that are checked will be passed back to the server, whereas all the hidden fields will always be passed so the lengths of the arrays will differ and the keys wont correspond.
The solution to this is actually relatively simple - you just need to specify the keys for the condition array so you can match the values up again. Something like this:
HTML:
<tr>
<td>
<input type='hidden' name='condition[100001]' value='good' />
<input type='checkbox' name='delete[]' value='100001' />
</td>
</tr>
<tr>
<td>
<input type='hidden' name='condition[100002]' value='new' />
<input type='checkbox' name='delete[]' value='100002' />
</td>
</tr>
PHP:
foreach ($_POST['delete'] as $delete) {
$condition = $_POST['condition'][$delete];
// Do stuff
}
This ties the values in the $_POST['condition'] array back up with the $_POST['delete'] array so everything will match up again.
EDIT
The way the keys are being created above is not great and in retrospect it is the wrong way to do it.
To demonstrate the right way to do it, let's imagine we have the following array, nice and simple:
$books = array(
10001 => 'good',
10002 => 'new',
10003 => 'new',
10004 => 'good'
);
What we need to do is tie up the two inputs that are associated with each book, which means we need a set of key/value pairs that can be matched up. That sounds like an array to me. But unlike the example above, the keys should be irrelevant to the data - they don't need to mean anything, because all we want is the data.
What we need to do is specify every single key explicitly (no stack-style array pushes) and make the keys agnostic of the data they relate to.
We can do this:
$i = 0;
foreach ($books as $isbn => $condition) {
echo "
<tr>
<td>
<input type='hidden' name='condition[$i]' value='$condition' />
<input type='checkbox' name='delete[$i]' value='$isbn' />
</td>
</tr>
";
$i++;
}
...and then, when the form is submitted, we can do this:
// We still base our code on $_POST['delete'] - because this is the array that
// depends on the user input. This time, though, we'll look at the keys as well
foreach ($_POST['delete'] as $key => $isbn) {
$condition = $_POST['condition'][$key];
// Do stuff
}

I'm a little confused about what you are asking, but I think I can simplify this for you. I don't know how you are generating the values for the hidden fields, are they hard coded? Regardless, this system would work much better if it were simplified.
Try this out....
This will combine the info for the numbers and condition, then it will split them on the backend for handling. This way the information is passed at the same time.
<tr>
<td>
<input type='checkbox' name='delete[]' value='100001-good' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='delete[]' value='100002-new' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='delete[]' value='100003-new' />
</td>
</tr>
<?php
if(isset($_POST['deleteInventoryBook'])){
if(isset($_POST['delete']) && is_array($_POST['delete'])){
foreach($_POST['delete'] as $checkbox){
$checkbox = explode('-', $checkbox);
echo $checkbox[1];
echo '<br />';
echo $checkbox[0];
echo '<br />';
}
}else{
echo "No values have been set";
}
}
?>
Again, I don't know if this is helpful or not because I was a little misunderstood about what exactly you were trying to achieve, but I hope it was helpful.

You're going to have to find a creative way to pass multiple hidden fields as an array to the PHP handler, or change how that data is collected. A "serialized" array seems to be the best bet.
This StackOverflow answer really outlines what you can do, and should still match your script's behavior. Good luck!

Related

Laravel Handling radio button values

I have a dynamically formed table with radio buttons to choose pass or fail in each rows. Below are my codes:
<form name="form2" method="post" action="/admin/testresults/update/added">
<?php if(isset($rows)){ $i=1; $pass=$ fail='' ; foreach ($rows as $row) { (($row->result == 1) ? $pass='checked' : $fail='checked'); print "
<tr>
<td>".$i."</td>
<td>".$row->name." ".$row->last_name."</td>
<td>
<input type='radio' name='".$row->userId."' value='1' ".$pass.">Pass
<br/>
<input type='radio' name='".$row->userId."' value='0' ".$fail.">Fail
<input type='hidden' name='".$row->userId."' value='".$row->userId."' </td>
</tr>
"; $i++; } print "
<tr>
<td colspan='3'>
<input class='ember-view btn btn-danger' type='submit' />
</td>
</tr>"; } ?>
</form>
I'm using the below codes in my controller:
$inputs = Input::get();
foreach($inputs as $input){
TestResults::updateCandidate($input);
}
What I want to pass into updateCandidate() is the student id and the selected radio button value (1/0). How can I do this?
Thanks
Firstly, I agree with #Chelius comments, look at laravel's documentation around blade templating and #if / #foreach and the use of {{ Form::input }}.
However in answer to your question - you will need to name you inputs better to retrieve the user id and the verbose PHP version should end up looking like this:
<td>
<input type='radio' name='results[".$row->userId."]' value='1' ".$pass.">Pass
<br/>
<input type='radio' name='results[".$row->userId."]' value='0' ".$fail.">Fail
<input type='hidden' name='".$row->userId."' value='".$row->userId."'
</td>
When processing, your code should then be:
$inputs = Input::get();
foreach($inputs['results'] as $userId => $result){
TestResults::updateCandidate($userId, $result);
}
Note that you may need to update your "updateCandidate" function to accept the user id and the result.

How to set the radio buttons for the attendance record PHP CSS?

I want to create an attendance record form where teacher can record attendance of the students and send it to database to store. Here I am using radio buttons and I want these buttons to only select either present or absent or authorise however right now it is not implementing what I want to do. Right now the selection of the radio buttons is not working properly so can you please me to put the radio buttons in specific way so that it selects only present or absent or authorise. I think we have to use CSS or javaScript for this HTML form syntax but the question is how. Thank you in advance.
echo '<table action="process.php" method="POST" class="tableEchoPupilAttendance" border="1">
<tr>
<th>Image</th>
<th>Name</th>
<th>Present</th>
<th>Absent</th>
<th>Authorise</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>
<td><img width='70' height='60' src='data:image/jpeg;base64,".base64_encode($row['image'])."'/></td>
<td>" .$row['name']. $row['surname']."</td>
<td> <input type='radio' name='present' value=''/> </td>
<td> <input type='radio' name='absent' value=''/> </td>
<td> <input type='radio' name='late' value=''/> </td>
</tr>";
}
echo "</table>";
Radio buttons are grouped by the name attribute. To have just one of the three radio buttons on each row selectable, their names must be the same, and their desired values stored in the value attribute.
I think it's fair to assume you have an id of some sort on your result rows. Therefore the following code might work:
while ($row = mysqli_fetch_array($result)) {
?>
<td><input type="radio" name="att[<?=$row['id'];?>]" value="present" /><td>
<td><input type="radio" name="att[<?=$row['id'];?>]" value="absent" /><td>
<td><input type="radio" name="att[<?=$row['id'];?>]" value="late" /><td>
<?
}
Submitting this will give you an array with content such as this:
[1] => 'present',
[3] => 'absent',
[4] => 'present',
[6] => 'late'
Using numeric values is usually a good idea, however the code won't be as readable.
Radio buttons are grouped only if they have the same name. So what you want to do is:
<td> <input type='radio' name='attendance[<?php print $row['id']; ?>]' value='present'/> </td>
<td> <input type='radio' name='attendance[<?php print $row['id']; ?>]' value='absent'/> </td>
<td> <input type='radio' name='attendance[<?php print $row['id']; ?>]' value='late'/> </td>

Updating multiple rows in mysql/php from a form

I’m trying to update multiple rows in a mysqli table from an HTML form. The data seems to be getting from the form to my "update database" page. But it’s not going into the database.
Here’s the relevant part of the form:
for($i=0;$i<$rowcount;$i++)
{
$row = mysqli_fetch_array($result);
echo "<tr>
<td> $row[SubFirstName] $row[SubLastName] </td>
<td> $row[PerfFirstName] $row[PerfLastName] </td>
<td style='display:none'><input type='text' class='input' name='PerformerID[]' value= '$row[PerformerID]' /> Years</td>
<td><input type='text' class='input' size= '5' name='GKYears[]' value= '$row[GKYears]' /> Years</td>
</tr>";
}
And here’s the code to insert the values into the database:
for($i=0;$i<$count;$i++)
{
mysqli_query($con, "UPDATE Performers SET
GKYears = '$_POST[GKYears][$i]'
WHERE PerformerID = '$_POST[PerformerID][$i]'");
}
When I do a var_dump of the POST data, it all seems to be there. Can someone explain how to fix this, and why it’s wrong? I’ve got other more complex variants of the same issue for the other pages.
Bad structure. Don't use CSS to simulate a hidden form field, and you don't even need the hidden field:
echo <<<EOL
<tr>
<td>... name stuff ...</td>
<td>... perf stuff ...</td>
<td><input type="text" name="GKYears[{$row['PerformerID']}]" value="{$row['GKYears']}" /></td>
</tr>
EOL;
Note how the ID value gets embedded in the field name, so you'll end up with
<input ... name="GKYears[42]" ... />
<input ... name="GKYears[103]" ... />
Then your PHP-side stuff becomes simply:
foreach($_POST['GKYears'] as $rowID => $value) {
... update db for record Id $rowID with value $value
}
Beyond that, your code is gaping wide and just begging for an SQL injection attack.

What is the correct syntax with nested for() loops in php and has differentiating increments?

I am trying to build a loop structure where I know that maximum # of loops and where there is a separate increment increase for certain fields/inputs. With this in mind I am thinking that I should pursue a nested for() loop structure.
As an example, let's say that the echoed goal, might look something like this:
<table>
<tr>
<td><input id="1" secondaryId="1" ></td>
<td><input id="2" secondaryId="1" ></td>
<td><input id="3" secondaryId="1" ></td>
</tr>
<tr>
<td><input id="4" secondaryId="2" ></td>
<td><input id="5" secondaryId="2" ></td>
<td><input id="6" secondaryId="2" ></td>
</tr>
<tr>
<td><input id="7" secondaryId="3" ></td>
<td><input id="8" secondaryId="3" ></td>
<td><input id="9" secondaryId="3" ></td>
</tr>
<!-- etc -->
</table>
So the id in this example increase by one at every input but the secondaryId increases by after every three inputs. To help further visualize, consider the follow:
I tried some things along this line for code:
<?php
echo"<table>";
for ($t=1;$t<4;$t++){
echo"<tr>";
for($y=1;$y<4;$y++){
echo"<td><input id='$y' secondaryId='$t'></td>";
}
echo"</tr>";
}
echo"</table>";
?>
Quite obviously it is not working and echo's back this instead:
I see exactly why the problem is occurring, because at every iteration(right word?) of the parent loop, the $y variable is reset back to 1.
How can I manipulate the loop(s) so that $y increments throughout the loop(s)? Is there a foreach combination that I ought to have considered?
Also, let's say that the above "id" and "secondaryId" type attributes are fixed and cannot be changed.
I have considered the last resort of just manually creating the field of inputs manually with the help of excel, but this seems laborious and promisses problems of debugging considering the field of inputs that I want to build is 50 rows (<tr>) by 23 columns (<td>)
> UPDATE:
I accepted Fabio's answer as it did work without fail, I wish I could have also accepted Maiden B.'s answer as this led me to create a mathematical solution in a single loop.
The code I will end up using is:
$m = 0;
echo"<table>";
for($y=1;$y<4;$y++){
echo"<tr><td>
<input id='".(1 + ($m*3))."' secondaryId='$y' >
<input id='".(2 + ($m*3))."' secondaryId='$y' >
<input id='".(3 + ($m*3))."' secondaryId='$y' >
</td></tr>";
$m++;
}
echo"</table>";
I think you just need to use other variables wich will count both your loop according with your needs
$m = 1;
$l = 1;
echo"<table>";
for ($t=1;$t<4;$t++){
echo"<tr>";
for($y=1;$y<4;$y++){
echo"<td><input id='$m' secondaryId='$l'></td>";
$m++; //we increment here for ipunt id
}
$l++; //we increment here for secondaryId
echo"</tr>";
}
echo"</table>";
This will output
<table>
<tr>
<td><input id='1' secondaryId='1'></td>
<td><input id='2' secondaryId='1'></td>
<td><input id='3' secondaryId='1'></td>
</tr>
<tr>
<td><input id='4' secondaryId='2'></td>
<td><input id='5' secondaryId='2'></td>
<td><input id='6' secondaryId='2'></td>
</tr>
<tr>
<td><input id='7' secondaryId='3'></td>
<td><input id='8' secondaryId='3'></td>
<td><input id='9' secondaryId='3'></td>
</tr>
</table>
You need to not reset the first input id. e.g.
echo"<table>";
$inputId = 1;
for ($t=1;$t<4;$t++){
echo"<tr>";
for($y=1;$y<4;$y++){
echo"<td><input id='$inputId' secondaryId='$y'></td>";
$inputId++;
}
echo"</tr>";
}
echo"</table>";
For the "echoed goal" it might be enough to use only 1 for loop. Your "id" attribute would contain the iterating variable $i and your "secondaryId" attribute would contain ($i div 3) + 1:
for ($i=1; $i <= $max; $i++) {
printf('<td><input id="%d" secondaryId="%d" ></td>', $i, ($i/3)+1);
}
The catch is to only increment one variable ($i) and let another value increment only when $i crosses certain limits (in this case every 3 steps).
The entire code would look something like this:
<table>
<tr>
<?php
for ($i=1; $i <= $max; $i++) {
printf('<td><input id="%d" secondaryId="%d" ></td>', $i, ($i/3)+1);
if ($i % 3 == 0) { // boundary reached
echo "</tr><tr>";
}
</tr>
</table>
I hope you get the point.
You Should Try This :-
<?php
echo"<table>";
$ids = 1;
for ($t=1;$t<4;$t++)
{
echo"<tr>";
for($y=1;$y<4;$y++)
{
echo"<td><input id='$ids' secondaryId='$t'></td>";
$ids++;
}
echo"</tr>";
}
echo"</table>";
?>

performing math on number array values in PHP

Ok, not exactly what I was expecting...I didn't know my code was so ureadable...sorry! What can I do to fix it? I really would like to just accomplish the (what I thought was) simple math to get totals. I've looked everywhere and read so much information on arrays and obviously I am just not grasping the concept...any more help is welcomed and would be GREATLY appreciated!
I’m creating a mock order form that has radio buttons, checkboxes and uses arrays to show the total purchase amount. I have a form that is working except for that I can't get the total amount from the two different arrays i have. $total = $extras + $additional isn't working and honestly, i should have known it couldn’t be that easy! ... Any suggestions on what formula to use so that I can get a total dollar amount of all of the options that are selected? Also, can anyone help me so that checkbox items are listed in a new row, and not a whole new table?
Thanks in advance!
A couple more things: I have to keep this in a redux and would like to keep the output in the table like it is...other than that, feel free to change whatever you want/need.
I’m new to PHP arrays and seem to only be having difficulties when it comes to their values, but since I know how important arrays are in PHP I would like to see how they work!
<?php
/*This stuff is only here because I want to make sure
there are 2 decimal places in the final numbers since
I'm dealing in "money" values*/
$total = number_format ($total,2);
$value = number_format ($value,2);
$additional = number_format ($additional,2);
$value = array("Short Trip"=>15.99, "Long Trip"=>28.99, "Overnight"=>10.99 "Forever"=>99.99);
if(isset($_POST['travel'])) {
$extras = array("Hair Brush"=>1.50, "Shampoo"=>1.50, "Toothpaste"=>1.50,
"Cream Rinse"=>1.50, "Tooth Brush"=>1.50,
"Shower Cap"=>1.50, "Washcloth"=>1.50, "Mouthwash"=>1.50);
if (isset($_POST['extras'])) {
foreach ($_POST['extras'] as $additional) {
echo "<table border =\"2\">
<tr><td>Item</td><td>Charges</td></tr>
<tr><td>".$_POST['travel']."</td>
<td> $".$value[$_POST['travel']]."</td></tr>
<tr>
<td>".$additional."</td>
<td> $".$extras[$additional]."</td>
</tr>
<tr><td>Your total</td> <td>".$total."</td></tr>
</table>";
}
}
}
?>
<html>
<body>
<form action="" method="post">
<table border="2">
<tr>
<td colspan="2" align="center" scope="col">Stay Information</td>
</tr>
<tr>
<td><input type="radio" name="travel" value="Short Trip" />Short trip $15.99</td>
<td><input type="radio" name="travel" value="Long Trip" />Long trip $28.99</td>
</tr>
<tr>
<td><input type="radio" name="travel" value="Overnight" />Overnight $10.99</td>
<td><input type="radio" name="travel" value="Forever" />Forever $99.99</td>
</tr>
</table>
<table border="2">
<tr>
<td colspan="2" scope="col">What will you need?($1.50 each)</td>
</tr>
<tr>
<td><input type="checkbox" name="extras[]" value="Hair Brush" />Hair Brush</td>
<td><input type="checkbox" name="extras[]" value="Shampoo" />Shampoo</td></tr>
<tr>
<tr><td><input type="checkbox" name="extras[]" value="Toothpaste" />Toothpaste</td>
<td><input type="checkbox" name="extras[]" value="Cream Rinse" />Cream Rinse</td></tr>
</tr>
<tr>
<td><input type="checkbox" name="extras[]" value="Tooth Brush" />Tooth Brush</td>
<td><input type="checkbox" name="extras[]" value="Shower Cap" />Shower Cap</td></tr>
<tr>
<tr><td><input type="checkbox" name="extras[]" value="Washcloth" />Washcloth</td>
<td><input type="checkbox" name="extras[]" value="Mouthwash" />Mouthwash</td></tr>
</tr>
<tr><td colspan="2">
<input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>
The comments have pointed out some issues, the main one being the formatting of your code. Indeed, when trying to figure out what one did wrong in a script, confusing formatting can add hours of wasted time.
The first thing you might notice is that your $value array is missing a comma.
$value = array("Short Trip"=>15.99, "Long Trip"=>28.99, "Overnight"=>10.99 "Forever"=>99.99)
// comma here -----------------------------------------------------------^
Formatting is to some degree a matter of style, but the main point is readability, so that you can more easily catch mistakes like this.
Here is a condensed version of something what your script might look like:
<?php
$value = array(
"Short Trip" => 15.99,
"Long Trip" => 28.99,
"Overnight" => 10.99,
"Forever" => 99.99
);
$extras = array(
"Hair Brush" => 1.50,
"Shampoo" => 1.50,
"Toothpaste" => 1.50,
"Cream Rinse" => 1.50,
"Tooth Brush" => 1.50,
"Shower Cap" => 1.50,
"Washcloth" => 1.50,
"Mouthwash" => 1.50
);
// combine condititions
if (isset($_POST['travel']) && isset($_POST['extras'])) {
$total = $value[$_POST['travel']];
// start table html (before foreach loop)
// store html in a variable to print later
$html = "<table border =\"2\">
<tr>
<td>Item</td>
<td>Charges</td>
</tr>
<tr>
<td>" . $_POST['travel'] . "</td>
<td> $" . $total . "</td>
</tr>";
foreach ($_POST['extras'] as $additional) {
// add a row per extra
$html .= "<tr>
<td>" . $additional . "</td>
<td> $" . $extras[$additional] . "</td>
</tr>";
// increment total
$total += $extras[$additional];
}
$html .= "<tr>
<td>Your total</td>
<td>" . $total . "</td>
</tr>
</table>";
}
?>
<html>
<body>
<form action="" method="post">
<?php
if (isset($html)) {
echo $html;
}
?>
<table border="2">
.....
There may be further issues, as I'm not clear on which part you're having trouble, but they will now be much easier to debug.
Impressive code Doug. I hate to tell you, but I think there may be one more error. I can't figure out why, but if anyone else runs this code they would see that the math is only performed on his $1.50 "additional" items-- There isn't a working collective total.

Categories