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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With