I'd like some help with a PHP form. The user on my form can select multiple products and amount of each products - I'm wondering, how can I make so that when the form is sent I can see what products and how much of each product the user has chosen in the mail?
The product list is in
and the amount is a select dropdown. <ul class="list-group checked-list-box">
<div class="col-xs-6">
<li class="list-group-item" data-style="button">Product 1</li>
</div>
<div class="col-xs-6">
<select class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</ul>
<ul class="list-group checked-list-box">
<div class="col-xs-6">
<li class="list-group-item" data-style="button">Product 2</li>
</div>
<div class="col-xs-6">
<select class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</ul>
Thank you for your answers.
Add name="amount[]"
to both/all selects
<select class="form-control" name="amount[PRODUCT_ID_GOES_THERE]">
<!-- eg. <select class="form-control" name="amount[<?php echo $product_id ?>]"> -->
and then you will have values from them in:
$_POST['amount'][24] // amount of product with ID=24
$_POST['amount'][2] // amount of product with ID=2
I really hope you are not building your product list by adding the same code over and over for each product.
There is a code approach called DRY, which means Don't Repeat Yourself. The benefit will come to you when you decide to make a change to the code and need to repeat that change multiple times.
Your code could look like this:
$my_products = array(
'343' => 'Product 1',
'4' => 'Product 2'
); // these values could be stored and retrieved from database
foreach ( $my_products as $key => $value ) {
echo "<ul class=\"list-group checked-list-box\">";
echo "<div class=\"col-xs-6\">";
echo "<li class=\"list-group-item\" data-style=\"button\">$value</li>";
echo "</div>";
echo "<div class=\"col-xs-6\">";
echo "<select class=\"form-control\" name=\"quantity[$key]>\"";
for ( $i = 0; $i <= 10; $i++) echo "<option value=\"$i\">$i</option>";
echo "</select>";
echo "</div>";
echo "</ul>";
}
Now if you want to add products, all you need to do is add an id and name to the $my_products
array. If you want to change the code, you only have to change it in one spot.