Store data from a dynamically generated form in an array - php

I have created a for loop that generates a form div repeatedly:
for ($i = 1; $i <= $noOfTanks; $i++) {
echo '<div class="';
echo $col;
echo '"><img id="tank" src="img/tank.svg" alt="Tank"></br>
<label for="tankName';
echo $i;
echo '">Tank Name ';
echo $i;
echo '</label>
<input type="text" id="tankName';
echo $i;
echo '" name="tankName';
echo $i;
echo '"></br>
<label class="rightT" for="tankVolume';
echo $i;
echo '">Tank Volume ';
echo $i;
echo '</label>
<input class="rightT" type="text" id="tankVolume';
echo $i;
echo '" name="tankVolume';
echo $i;
echo '"><p>L</p>
</div>';}
The code generated a number of inputs. I want to gather all this input values into two arrays tankName[], tankVolume[]. I am struggling to understand how to use $_POST to do this.
Thanks for any help.

Use array of inputs.
Example:
<input class="rightT" type="text" id="tankVolume1" name="tankVolume[]"/>

Related

Generate multiple checkboxes and evaluate them

I have a table that displays every unapproved leave, it looks like this:
For each unapproved there will be a new row, so another checkbox, but the name of the checkbox will be the same or slightly different(name="approve1"). Personally I don't think that's good practice...
Also the evaluation isn't really good, because it has to go into the database.
<form role="form" method="post" action="" id="form">
<h2><?php echo $title ?></h2>
<?php
$page = date('F');
$page = lcfirst($page);
echo "<p><a href='$page.php'>Back</a></p>";
?>
<hr>
<?php
if($i == 0){
echo "<h3>No unapproved leaves.</h3>";
}else{
echo '<table class="table table-striped table-hover">';
echo '<thead>';
echo '<th>';
echo 'Start';
echo '</th>';
echo '<th>';
echo 'End';
echo '</th>';
echo '<th>';
echo 'Employee';
echo '</th>';
echo '<th>';
echo 'Approve';
echo '</th>';
echo '</thead>';
echo '<tbody>';
for($j =0; $j < $i; $j++){
echo '<tr>';
echo '<td>';
echo $unapproved[$j]['start'];
echo '</td>';
echo '<td>';
echo $unapproved[$j]['end'];
echo '</td>';
echo '<td>';
$id = $unapproved[$j]['employee_FK'];
$result = mysql_query("select name, surname from employee where employee_ID = $id");
while ($row = mysql_fetch_assoc($result)) {
$employee[] = $row;
}
echo $employee[0]['name'], " ", $employee[0]['surname'];
echo '</td>';
echo '<td>';
echo '<input type="checkbox" name="approve" value="1" id="approve">';
echo '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
}
?>
<input type="submit" name="submit" value="Submit" class="btn" >
</div>
</div>
</form>
Can anyone think of a better, easier solution?
The practice for tabular data in most frameworks is to name them Model[id][field], so in your example it would look like "<input type='checkbox' name='leave[$j][approved]' value='1' id='leave_$j_approved'>".
Then you can easily access your data by iterating the post data like so:
foreach($_POST['leave'] as $id => $values) {
}
use checkbox name like this
<input type="checkbox" name="approve[]" value="<?php $your_row_id; ?>" id="approve">
here $your_row_id means unique id of a row in database.
And in post you will get an array named approve with all the selected values.
Parse that array using foreach.
You can generate checkboxes using a array notation in the "name" attribute.
<input type="checkbox" name="approve[]" value="1" id="approve">
After on send, you can recover values using array notation $_GET['approve'][0], ...
You can transfer arrays via HTTP :
echo '<input type="checkbox" name="approve[]" value="', $id, ']" id="approve">';
Now $_GET['approve'] will be an array which only contains values of checked boxes.
You can also specify the key associated with the value:
echo '<input type="checkbox" name="approve[', $id, ']" value="', $id, ']" id="approve">';

echo with attribute name for query purposes php pdo

<form method="POST" action="include/crud.php" enctype="multipart/form-data" >
<?php
foreach (LoadAnouncements() as $value){
/*echo "<div id='bb'></div>";*/
echo "<hr/>";
echo $value['searchresultwhat'];
echo "<br/>\n";
echo $value['searchresultwhen'];
echo "<br/>\n";
echo $value['searchresultwhere'];
echo "<hr/>";
/*echo "<div id='bb'></div>";*/
}
?>
</form>
I have this form that show an echo is there a way that I can add the attribute name in this echo so I can use it to query the database? I search for ideas if putting attribute to echo is possible but I haven't found anything yet any suggestion is appreciated
You are looking it?
<input type="text" name="searchresultwhat[]" value="<?php echo $value['searchresultwhat']; ?>" />
<input type="text" name="searchresultwhen[]" value="<?php echo $value['searchresultwhen']; ?>" />
<input type="text" name="searchresultwhere[]" value="<?php echo $value['searchresultwhere']; ?>" />
Edited
<?php
echo '<table>';
echo '<tr><th>What </th><th> When</th><th> Where</th><tr>';
foreach (LoadAnouncements() as $value){
echo "<tr><td>".$value['searchresultwhat']."</td>
<td>"$value['searchresultwhen']."</td>
<td>".$value['searchresultwhere']."</td>
</tr>";
}
echo '</table>';
?>
Do you want to add attribute to certain value in PHP? But you can't do it because $value['searchresultwhat'] and others of the kind are simple strings - as is! They can't send separated data (or attributes) with themself.
EDIT:
You can send seprated data about certain value using array:
$value['searchresultwhat'] = array("name", "value");
$value['searchresultwhen'] = array("name2", "2014-09-01");
$value['searchresultwhere'] = array("name3", "kittens");
echo $value['searchresultwhat'][0] . " is " . $value['searchresultwhat'][1];
echo $value['searchresultwhen'][0] . " = " . $value['searchresultwhen'][1];
echo $value['searchresultwhere'][0] . " has " . $value['searchresultwhere'][1];

calculating the sum of an array php

Hi im currently doing making a website that sells games as a project but im having problems calculating the sum for the price of the games
I have this loop which displays the games added into the basket
cart.php
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag" name="price" method="POST">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform">';
echo '<select name="quantity" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
echo '<input type="submit" value="update" />';
echo '</form>';
echo '<div class="quantity_update">';
echo '<form action="remove_item.php" method="POST">';
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
echo '<input type="submit" value="Remove Item" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<div id="delete_all">';
echo '<form action="delete_cart.php" method="POST">';
echo '<input id="hide_button" type="submit" value="Clear All" />';
$a=array($gamePrice);
echo array_sum($a);
echo '</form>';
echo '</div>';
?>
this is where im trying to calculate the total price
$a=array($gamePrice);
echo array_sum($a);
The reason this doesnt work, is because $gamePrice never is an array (unless you didnt provide all code). In the loop, it gets set to a new value, after the loop only the last one is stored.
Based on some hints in your code, I guessing this is a cart and you're looping through the cart. An easy way to get a total is like this:
$total = 0;
while( $itemsThatWeLoop){
// Some code here
$total+= $gamePrice*$quantity;
}
You add a variable which increments with the product's price
To explain the while-only-last-value-saved:
$i=0;
while( $i<=10){
$i= $i+1;
}
echo $i;
Will give 10. All other iterations $i gets set to a new value. The original value is not saved

How to fetch POST values of a dynamically generated form in php

this is my dynamically generated form that allows the user to input scores of students.my challenge is how to capture the specific subjectCode and its score because am using the subjectcode to store in the database .
<?php
$attributes=array('class'=>'','id'=>'');
echo form_open('scoreInsertion/insertScores',$attributes);
echo "<table>";
echo "<tr>";
echo "<td>";?>
<label for="admNo>">Admission Number<span class="required">*</span></label>
<?php echo form_error('admNo');
echo "</td>";
echo "<td>";?>
<input type="text" name="admNo" id="admNo" value="<?php echo set_value('admNo')?>" />
<?php echo "</tr>";
echo "<tr>";
echo "<td>";
?>
<label for="studentName>">Student Name<span class="required">*</span></label>
<?php echo form_error('studentName');
echo "</td>";
echo "<td>";?>
<input type="text" name="studentName" id="studentName" value="<?php echo $studentName?>" />
<?php echo "</tr>";
echo "<tr></tr>";
echo "<tr>";
echo "<td>";
?>
<label for="examCategory">Exam Category<span class="required">*</span></label>
<!--<tr><td><?php echo form_error('examCategory')?></td></tr>-->
<td>
<select name="examCategory">
<option value="">--Select Category--</option>
<?php
print_r($exams);
if(isset($exams) && is_array($exams)){
foreach($exams as $exam){
$examId=$exam->id;
$examName=$exam->category;
echo "<option value='$examId'>$examName</option>";
}
}
?>
</select></td><?php
echo "<tr></tr>";
echo "<tr>";
echo "<td>";
?>
<label for="term">Academic Term<span class="required">*</span></label>
<!--<tr><td><?php echo form_error('examCategory')?></td></tr>-->
<td>
<select name="term">
<option value="">--Academic Term--</option>
<?php
if(isset($terms) && is_array($terms)){
foreach($terms as $term){
$termId=$term->termId;
$termName=$term->name;
echo "<option value='$termId'>$termName</option>";
}
}
?>
</select></td>
<?php
echo "<tr>";
//loop through the subjects array and display them on the view
if(isset($subjects) && is_array($subjects)){
foreach($subjects as $subject){
$subjectName=$subject->subName;
$subjectCode=$subject->subCode;
echo "<tr>";
echo "<tr></tr>";
echo "<td>";?>
<label for="<?php echo $subjectName?>"><?php echo $subjectName;?><span class="required">*</span></label>
<?php echo form_error($subjectName);
echo "</td>";
echo "<td>";?>
<input type="text" name="<?php echo $subjectCode?>" id="<?php echo $subjectName?>" value="<?php echo set_value($subjectCode)?>" />
<?php echo "</tr>";
}
}
?>
<?php echo "<tr>";echo "<td>";
echo form_submit('submit','Submit');
echo "</td>";
echo "</tr>";
?>
</p>
<?php
echo "</table>";
echo form_close();
?>
PHP script to process the above POST details is below:
function insertScores(){
$admNo=$this->input->post('admNo');
$term=$this->input->post('term');
//get the post variables from the Form
$posted = $this->input->post();
$x = array_keys($posted);
foreach($x as $y) {
echo $y ." = ". $_POST[$y]."<br/>";
echo "<br>";
//write the sql
$form_data=array(
'admNo' =>$admNo,
'subCode'=>$y,
'termId'=>$term,
'score'=>$_POST[$y]
);
print_r($form_data);
$this->SaveForm($form_data);
}
}
If that really has to be, you could set a specific prefix for the name attribute and then look for a key starting with that prefix among your $_POST keys. Something like that:
<input type="text"
name="subject_<?php echo $subjectCode?>"
id="<?php echo $subjectName?>"
value="<?php echo set_value($subjectCode)?>" />
Then search for it in the $_POST array.
$subjectCode = null;
foreach (array_keys($_POST) as $index) {
if (strpos($index, 'subject_') === 0) { // you found the needed element
// get its value and save it in a variable
$subjectCode = $_POST[$index];
break;
}
}
This code solved my problem, I fetch the subCode using admNo in the db then compare with the POST names.
$subjects=$this->subjectModel->get_subjects();
foreach($subjects as $subject){
$subCode= $subject->subCode;
foreach($_POST as $key => $value){
//print_r($key);
//print_r($value);
$form_data=array();
if($key == $subCode){
//echo $subCode. "=". $value;
//write the sql for insertion into the database
$form_data = array(
'admNo'=>$admNo,
'subCode'=>$subCode,
'termId'=>$term,
'formId'=>$formstudy,
'score'=>$value,
'year'=>$year
);
$this->SaveForm($form_data);
}
}
}

How do I get values from a table out of a foreach loop?

What I'm doing is trying to set up a page where users can see their created tools and delete them whenever they want. I'm querying three different tables and putting the results into an array. Once those values are in an array, a foreach loop goes through and populates a table with all the information in a table, like so:
$counter = 1;
echo '<table>'
foreach ($recent_saved_tools as $key => $value) {
echo '<tr name="item'.$counter.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table'].'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete'].'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield'].'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
$counter ++;
}
echo '</table>';
The problem is whenever I run the SQL query, no matter what button I click it always takes the values from the last table row. I know it has something to do with the way they're named (multiple elements have the same name) but I'm at a loss on how to fix this. Any help would be appreciated.
Here's the query I'm using to delete the item:
$query = 'UPDATE '.$value['table'].' SET '.$value['delete'].' = 1 WHERE '.$value['idfield'].' = '.$value['id'];
$sql->query($query);
EDIT: added delete code
Every row has some inputs which are posted to the server. They have the same names - for every row. You could change it like this:
echo '<input type="hidden" name="tablename'.$counter.'" value="'.$value['table'].'" />';
Then you can use $_POST['tablename'.$rownr] in your delete code.
Doesn't look like you're closing the anywhere...
What results return from the query?
What output are you expecting?
try making it a for loop in stead and adding the variable to the end.
$array;
$counter = count($array);
echo '<table>'
for($i = 0; $i < $counter - 1; $i++) {
echo '<tr name="item'.$i.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table']. $i'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete']. $i'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield']. $i'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
}
echo '</table>';

Categories