Post HTML elements array to PHP - php

Here is the snapshoot of my form. The input values under LPO (1st column) are hidden, I just showed them here to show complete form.
if color_id (first left most inputbox) is 37 its DB value is BB552 as displayed. And if its 3, the value of that color is BB110, but when its 0, it means a user has selected Custom and written a value by him self in the third row it is FFBBBAA.
I need to submit the form to PHP
The field names are as follows
color_id[] <-- Hidden input
order_id[] <-- Hidden input
subcolor_id[] <-- Select
subcolor_string[] <-- Input
material_id[] <-- Select
weight[] <-- input
When I post the form, in PHP
<?PHP
$count = count($_POST['weight']);
for($i = 0; $i < $count; $i++){
$color_id = $_POST['color_id'][$i];
$order_id = $_POST['order_id'][$i];
$material_id = $_POST['material_id'][$i];
$weight = $_POST['weight'][$i];
// i can count one post item and can iterate over all.
if($color_id == 0){
$color_id = $_POST['subcolor_id'][$i]; // this give me wrong result;
}
}
So when 0 is there, admin approving this form, can leave it to custom or change the color back to some value from DB
I want to know what are the possibilities for getting the proper sub color values if first hidden input color_id has 0.
So far the one which I thought of is to add two more hidden fields in Sub Color columns to match their index, but this will require me to completely re-write the del sub color code
Is there any other way which can save me from doing lots of alterations to this form?

as eds mentioned it totally makes sense.. u shud do this way
$j=0;
$count = count($_POST['weight']);
for($i = 0; $i < $count; $i++){
$color_id = $_POST['color_id'][$i];
$order_id = $_POST['order_id'][$i];
$material_id = $_POST['material_id'][$i];
$weight = $_POST['weight'][$i];
// i can count one post item and can iterate over all.
if($color_id == 0){
$color_id = $_POST['subcolor_id'][$j]; // this give me wrong result;
$j++;
}
}
this shud solve your problem..

Your other option is to declare another iterator $j outside of the loop, starting at 0, and manually incrementing that iterator after you read a subcolor each time. Then it should always be the index of the next subcolor_id you need to read.

Related

Restore array items after every iteration in PHP

I am trying to restore all array items after each for loop iteration. This I need to set Laravel validation Rule::notIn($arry)
I have an array of station_id generated by cloned input fields. I want to check if all cloned station ids are unique, and so be sure that no repeated station in the metro route.
For cloned fields, I am setting up a rule using for a loop by counting cloned items.
So the issue is, I want to use `Rule::notIn($stationIds) except the current iteration item id so I can validate by checking the current id is not in the rest of the array items.
public function rules()
{
// getting all input fields value
$rStationIds = $this->get('station_id')
...
// get the max number of input
$counter = $this->getMaxCount($rStationIds, ...);
$rules = [];
// loop through each item
for ($r = 0; $r < $counter; $r++) {
unset($rStationIds[$r]);
$rules['station_id'][$r] = ['required', 'int', Rule::notIn($rStationIds)];
}
...
}
The problem in the above code is that when I unset($var) the current item, it never reset back with the original array elements; thus, the last field will have nothing to compare because the array will get empty.
I am okay with any other approach as well to check the unique item for the cloned station id fields.
Change your loop to:
// loop through each item
for ($r = 0; $r < $counter; $r++) {
$temp = $rStationIds[$r];
unset($rStationIds[$r]);
$rules['station_id'][$r] = ['required', 'int', Rule::notIn($rStationIds)];
$rStationIds[$r] = $temp;
}

PHP - Get input from dynamically added html table rows

I have the following Fiddle set up here Fiddle
As you can see, I am able to add inputs by clicking the Add Row button.
All inputs that are added have a unique id and name. The problem is, I cant just do something like
$actionInput = $_POST["actionInput"];
Because I might need
$actionInput1 = $_POST["actionInput1"];
$actionInput2 = $_POST["actionInput2"];
$actionInput3 = $_POST["actionInput3"];
Depending on how many rows are added. So how can I get all the inputs without knowing what inputs I need to grab?
Thanks
Actually, you need to maintain counter in hidden, which you will get at the time of posting the form in case you don't want to maintain elements as array, otherwise you can put elements as array as described below:
<input type=text name="inputs[]" />
Name your inputs with array boundary, like:
<input type=text name="actioninput[]" />
now you can itreate throught them in you POST or GET ( depends ) array:
print_r($_POST);
Assuming your JSFiddle works fine for you, following are the steps.
1) Get keys of $_POST.
2) Get maximum counter value from keys.
3) Take a for loop from 0 to count of post.
4) If counter is 0, no suffix, else, add counter as suffix.
5) Now, you get posted variable.
6) Repeat it for every element in rows.
<?php
$keys = array_keys($_POST);
$keys = implode(',', $keys);
$n = str_replace('actionInput', '', $keys);
$m = explode(',', $n);
$max = max($m);
for ($i=0 ; $i<=$max ; $i++) {
$suffix = ($i==0) ? '' : $i;
if (isset($_POST['actionInput' . $suffix])) {
echo "<br/>-".$_POST['actionInput' . $suffix];
}
}
replace name=actionInput with name=actionInput[]
it should be an array with same name
same thing will apply with all form fields generated dynamically whose values you'll need.
Change this line in Add row jquery event
return name + i to return name
Remove i from it and then
name=actionInput[]
print_r($_POST);
It will gives array of actioninput

Resetting a submitted form in Symfony 2

I'm mapping some data coming from the remote source into my entites. I'm using forms for this purpose. Here is a fragment of code that is responsible for mapping data onto entities:
$i = 0;
$x = 0;
foreach ($bestellerLists[0] as $bestsellerList) {
$List[$i] = new BestsellerList();
foreach ($bestsellerList['books'] as $book) {
$Book = new Book();
$bookForm = $this->bookForm;
$bookForm->setData($Book);
$bookForm->submit($book);
$List[$i]->addBook($Book);
unset($bookForm);
unset($Book);
$x = $x + 1;
}
$i = $i+ 1;
}
The problem that I cannot solve is that in the first iteration if the inner foreach loop, everything is well, entities get mapped, the first $Book is added to the current $List.
However, the second interation of the inner loop errors out with:
You cannot change the data of a submitted form.
As you can see, the $bookForm is assigned the value with $bookForm = $this->bookForm. At the end of the current iteration I unset $bookForm in order to create a new one at the next iteration.
I really do not get why Symfony would complain about changing the data of a submitted form. A new empty form should be used at each iteration. Any idea what I might be missing here?

How to remove a blank array from option input in php

Hi I´m trying to put an array into option input. But the problem is I get one blank option.
I want to remove it.
Here is what I'm trying to do:
<select name "x">
$myarray=array('black','blue','brown');
for ($i=0;$i<=count($myarray);$i++){
if ( $row['colur']==$myarray[$i]) {//if value in database = array$i
echo"<option value='$myarray[$i]' selected>$myarray[$i]</option>";
} else {
echo"<option value='$myarray[$i]'>$myarray[$i]</option>";
}
}
You should loop one item less:
for ($i=0;$i < count($myarray);$i++) {
The last $i your loop "sees" is count($myarray) which is 3 in your case. However, because arrays are zero-indexed, item $myarray[3] doesn't exist (it goes from 0 to 2). The if fails and $myarray[3] is shown, which doesn't exist: you also get an error of level "notice" in your server logs (which should be the trigger to find this all out yourself).
To prevent all this, use foreach:
foreach ($myarray as $color) {
// use $color instead of $myarray[$i]
}
As array index start from 0 to (array length -1), you should mention your for loop accordingly i.e
$array_length = count($myarray);
for ($i=0;$i < $array_length;$i++) {
//your code
}

Create PHP array's on the fly

I am having the worst time trying to get this to work. In the following code, I am gathering data from a database query and trying to build a muti-dimensional array object that will keep totals and tally up some information in a specific way. The problem is that instead of getting a value that is incrementing as it should, the value seems to be suffering from the last value it was assigned problem. Here is the code:
$REVIEWS = array();
$USER_REVIEWS = array();
$USER_IMGREVS = array();
pseudo-code: loop here which iterates over the DB results creating
$date - which is into this function as its called for each day of month
$p1user - which is one of the users (there are 3) 'levels' of users
$hr - is the hour which is built from the transaction's timestamp
$hr = date('H', $row['P1TIMESTAMP']);
$p1user = $row['P1USER'];
$REVIEWS[$date] += 1;
$USER_REVIEWS[$date][$p1user][$hr] += 1;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];
print "PASS1<br/>\n";
print "Value of Total Reviews: [".$REVIEWS[$date]."]<br/>\n";
print "Value of User Reviews: [".$USER_REVIEWS[$date][$p1user][$hr]."]<br/>\n";
print "Value of Reviewed Images: [".$USER_IMGREVS[$date][$p1user][$hr]."]<br/>\n";
print "<br/><br/>\n";
So - the 'total reviews' increments by one, as it should, for each time i print this. SO far so good. The next two arrays will only print the last values they were assigned, and will not be added together like they should. Why not? I have attempted to do this another way by literally creating the arrays one by one and assigning them in whole to the array containing them - but that also does not seem to work. Any insights?
i don't know how you initilize your array, maybe this will help:
// replace this 2 lines:
$USER_REVIEWS[$date][$p1user][$hr] += 1;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];
// with this code:
if (!isset($USER_REVIEWS[$date]))
$USER_REVIEWS[$date] = array();
if (!isset($USER_REVIEWS[$date][$p1user]))
$USER_REVIEWS[$date][$p1user] = array();
if (!isset($USER_REVIEWS[$date][$p1user][$hr]))
$USER_REVIEWS[$date][$p1user][$hr] = 0;
$USER_REVIEWS[$date][$p1user][$hr] += 1;
if (!isset($USER_IMGREVS[$date]))
$USER_IMGREVS[$date] = array();
if (!isset($USER_IMGREVS[$date][$p1user]))
$USER_IMGREVS[$date][$p1user] = array();
if (!isset($USER_IMGREVS[$date][$p1user][$hr]))
$USER_IMGREVS[$date][$p1user][$hr] = 0;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];
Sir, I dont understand very well why your coed is not working, but in my first test, I would change these lines:
$count = 1;
$USER_REVIEWS[$count][$p1user][$hr] += 1;
$USER_IMGREVS[$count][$p1user][$hr] += $row['F5'];
$count++;
Please, check if this code helps you anyway.
Your print statements for those values rely on the value of $p1user:
print "Value of User Reviews: [".$USER_REVIEWS[$date][$p1user][$hr]."]<br/>\n";
print "Value of Reviewed Images: [".$USER_IMGREVS[$date][$p1user][$hr]."]<br/>\n";
If you want to print it for all users you should loop over all possible users rather than just using $p1user. Either that or add them up if you want their sum.
Edit: Something that was bugging me was your data structure. It doesn't seem to represent your data very well. In your loop why don't you build up useful information that you store at the base of the review array?

Categories