Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach value from POST from form

Tags:

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.

What would be the best way to loop through those items to get the values?

Here's what I have, which obviously isn't working.

extract($_POST);

$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop

while(${'item_name_' .$x} != '') {

echo ${'item_name' .$x};

$x++;

}

I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.

Thanks.

like image 607
Andelas Avatar asked Mar 29 '11 23:03

Andelas


1 Answers

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}
like image 100
Alp Avatar answered Oct 03 '22 12:10

Alp