PHP, Submitting a two dimensional table with TextBox to proccess - php

I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database.
Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.
So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.
I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful
Thanks a lot

I would suggest you just name the input elements as an array. something like:
<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">
<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">
or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.
Using the above form, you can process the data with something like this:
<?php
foreach($_POST['fruits'] as $company=>$row){
foreach($row as $fruit=>$quantity){
if(!is_numeric($quantity) || $quantity < 0){
$quantity = 0;
}
echo "You selected {$quantity} {$fruit} from {$company}";
}
}

I would try creating a multi dim array with the ID of the item as the first dimension. Like this:
<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />
Then, in your processing script:
foreach ($_POST['textbox'] as $row)
{
foreach ($row as $key => $val)
{
$q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
mysql_query($q);
}
}

Related

html checkbox arrays generating additional array elements on a change

Long time listener, first time caller. I am implementing a system to track who participates in various events. After defining the "activity" record, the plan is to populate another table with the list of members (lets say 60) who might have attended, then present a form for the organizer to 'check' who actually participated with the hours spent. This information is then passed by POST to update the database.
The issue deals with the array of Checkboxes, one for each participant, and correct handoffs to the DB update process. The problem is that the first time a checkbox is changed, either manually by the organizer or automatically to reflect a previous choice, it generates an extra element in the checkbox array, thereby throwing them all out of alignment with the other arrays. This link (Do checkbox inputs only post data if they're checked?) was the closest to the problem that I found, but did not address handling checkbox arrays.
I implemented the hidden checkbox approach per several posts, tried both absolute array indexing, and am I still get an extra array element every time. I even contemplated replacing the checkboxes with something less elegant like 2 radio buttons (Y/N) each or a two-value select field. I am definitely not an expert here and am willing to do the research and learn, but I've hit a dead-end.
Any ideas, workarounds, or links to other references for this would be appreciated.
Here is the code:
<?php
echo "<form action=\"index.php\" method=\"post\">";
$query = ((get stuff));
$result = mysqli_query($con, $query) or die ('Sorry, could not access the joined users+activitypart tables');
// extract and format all users for the activity
$i = 0;
while($row=mysqli_fetch_array($result, MYSQL_ASSOC))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$apidx[] = $row['apidx']; // Pointer to this user's record
$isParticipant[] = $row['isParticipant']; // checkbox value
$actduration[] = $row['actduration']; // Actual duration in hours spent
$role[] = $row['role']; // Role that this person held during this activity
?>
<input type="hidden" name="passidx[]" value="<? print $apidx[$i] ?>">
<input type="hidden" name="passpart[<? $i ?>]" value="0" />
<input type="checkbox" name="passpart[<? $i ?>]" value="1" <? if($isParticipant["$i"]) print "CHECKED" ?> />
<input type="text" name="passdura[]" size="7" value="<? print $actduration["$i"] ?>">
<?php
echo "$i $firstname $lastname<br>";
$i++;
}
?>
<!-- when done, pass all name field values to actusr08a -->
<br><input type="hidden" name="content" value="actusr08a">
<span class="form-field-no-caption">
<input type="submit" value="Submit">
</span>
</form>
So, When I load this page with 15 members, as a debug step, I count the 3 arrays and they all show 15, 15, 15 elements each at load time. If I click on 2 check-boxes, post it to the next page and do a count of the received arrays, two of the arrays (passidx, passdura) show 15 elements each, and the checkbox array (passpart) shows 17. since 2 checkboxes changed, seems they then post the change, thus the additional 2 elements. This is what I am trying to fix.

PHP multidimensional array from HTML form

I've got an HTML form that allows a user to submit details about one or more children. Each child can have one or more items.
My HTML form structure looks like this:
<input type="text" name="child[1][name]">
<input type="text" name="child[1][dob]">
I then have a table display for the items (as there are 2 fields per item) where the user can add/remove rows via Javascript. Example:
<table>
<tr>
<td><input type="text" name="child[1][item][name]"></td>
<td><input type="text" name="child[1][item][value]"></td>
</tr>
</table>
When I access this data, I'm inputting the child data into a table, then I need to access the items per child separately, so they can be stored in an 'items' table (with the child ID which I'll grab from the database insert).
In my PHP, I'm looking to achieve something like:
foreach($_POST['child'] as $child) {
$child_name = $child['name'];
$child_dob = $child['dob'];
// insert child data to children table
foreach($_POST['item'] as $item) {
$item_name = $item['name'];
$item_value = $item['value'];
// insert item data to items table
}
}
My problem is that without the items, the child array looks fine when I print_r($_POST['child']). However when I include the items as per my HTML above, the array only outputs the last item added (whether there is one or more). I'm not sure if I'm correctly specifying the array for items in the input tags, or how I should then access in the PHP.
If anyone has any suggestions about where my syntax may be wrong, or if perhaps I'm approaching this in the wrong way, that would be much appreciated.
Figured this out.
As suspected, the naming format was wrong for the item input fields, meaning the sub array for items wasn't being posted correctly.
Updated to:
<input type="text" name="child[1][item][1][name]">
<input type="text" name="child[1][item][1][value]">

How can we process a dynamic form in php

The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.

Processing multiple input fields with codeigniter?

The problem I am having is that my ecommerce script allows people to add products to their store. However, those products can have variants... like Color and those variants can have options, like Black, White, and Blue for example. The problem I am having is how exactly do I determine how many options they have entered. Eventually I will have a javascript function add a new input field if they click "add option" but for now I just made 3 input fields like so:
Variant Title:<input type="text" name="variant_title"><br>
Variant Option: <input type="text" name="variant_option_1"><br>
Variant Option: <input type="text" name="variant_option_2"><br>
Variant Option: <input type="text" name="variant_option_3"><br>
Now what I don't know how to do is loop through all the variant_options and if they are not empty add them to a database. I don't want to hard code it in with the names because I don't know how many options they will choose per variant.
I tried doing this:
$i = 1;
while($this->input->post('variant_option_$i') != '')
{
$variant_options[] = $this->post->input('variant_option_$i');
$i++;
}
But that does not seem to work, as the variant title gets added to the database, however the options do not.
The only thing I need a solution to is to how to actually grab those fields all at once. I was thinking a foreach loop but im not sure.
Thank you.
I would use an array of input fields instead:
Variant Title:<input type="text" name="variant_title"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Then check for the values like:
if (is_array($this->input->post('variant_option')):
foreach ($this->input->post('variant_option') as $value):
$variant_options[] = $value; // loop through...
endforeach;
endif;

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Categories