Reputation:
I had no problem on getting the values from HTML form but my problem is how to combine all values that I got in one array?
Example:
Quantity[]
is separated from CheckBox[]
. If the checkbox has been checked, only all values of it (Pizza ID, Name, Price and Quantity) should be transfer into one array.
Snippet Code:
<tbody>
<?php
$Row = 0;
while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC)){
$pizzaID = $Row['pizzaID'];
$pizzaName = $Row['pizzaName'];
$pizzaPrice = $Row['pizzaPrice'];
?>
<tr>
<td><?php echo $pizzaID; ?></td>
<td><?php echo $pizzaName; ?> </td>
<td><?php echo $pizzaPrice; ?> </td>
<td><input type = "number" name = "Quantities[]" placeholder = "0"/></td>
<td><input type = "checkbox" name = "CheckBox[]" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/></td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
<button type="submit" form="form1" value="Atc" name="atc" class="btn btn-warning">Add to Cart</button>
Back end:
<?php
$values = array();
$quantities = array();
if(isset($_POST['atc'])){
//Operation to retrieve all values from HTML CheckBox[] and Quantities[] since they are separated inputs
//And push all values that has been retrieved into same array
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
foreach($_POST['Quantities'] as $key => $value){
array_push($values, $value);
}
Current Output:
Desired Output:
How to achieve the desired output? Is my technique on getting the values from HTML (2 Separated arrays) is right? How to make all values to be combine in just one array?
Upvotes: 0
Views: 283
Reputation: 43
You could use the "associative array" style of naming your form inputs, as described in the PHP docs:
http://www.php.net/manual/en/faq.html.php#faq.html.arrays
Use your unique pizzaID
as the key for both input arrays:
(Include a string element (I've used id_
here) to ensure that it will be a string key that we will be working with later as the array functions work differently for numerically indexed arrays)
while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC))
{?>
<input type = "number" name = "Quantities[id_<?=$pizzaID?>]" id="qty<?php echo $cnt?>" placeholder = "0"/>
<input type = "checkbox" name = "CheckBox[id_<?=$pizzaID?>]" data-cnt="<?php echo $cnt?>" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/>
<?php }
When you read the POST values in, each named array will be in the format of key => [id => value]
.
You can then use the id key strings to unify the values in the 2 arrays using array_merge_recursive
.
$q = $_POST['Quantities'] ?? [];
$c = $_POST['CheckBox'] ?? [];
$merged = array_merge_recursive($q, $c);
This will combine all of the values associated with each pizzaId
key. The resulting array looks like this:
Array
(
[id_1] => Array
(
[0] => 1,Hawaiian,150
[1] => 23
)
[id_3] => Array
(
[0] => 3,Four Cheese,300
[1] => 33
)
)
Now you can squash these merged arrays to produce a single comma delimited list for each pizzaId:
$squashed = array_map(function($v){
return is_array($v)
? implode(',', $v)
: $v;
}, $merged);
The $squashed
array will now contain:
Array
(
[id_1] => 1,Hawaiian,150,23
[id_3] => 3,Four Cheese,300,33
)
The id_
prefix can then be stripped out of the keys if required.
One caveat would be that if the user has only submitted values for one of the 2 input fields, then the resulting array will only contain that single value and it would take further analysis to determine whether this was the Quantity
or Checkbox
value (e.g. checking against is_int()
could determine whether the value belonged to Quantity).
Upvotes: 1
Reputation: 14520
You'll get a better understanding of what is happening if you view the POSTed data as PHP sees it in your script. At the top of your PHP add:
print_r($_POST);
die();
And you'll see:
Array
(
[Quantities] => Array
(
[0] => 23
[1] =>
[2] => 33
)
[CheckBox] => Array
(
[0] => 1,Hawaiian,150
[1] => 3,Four Cheese,300
)
Next, array_push
simply appends elements to the end of an array. So you're just joining those 2 arrays one after the other, without preserving the fact that the elements relate to each other.
The next problem is that checkboxes don't appear in the POSTed data at all if they are not checked. You can see that there are only 2 elements in the Checkbox
array, even though you have 5 pizzas in the form. That means you can't connect elements from the Quantities
array and the CheckBox
array using the key. Key 1 in Quantities
corresponds to Bacon and Cheese
, but key 1 in CheckBox
corresponds to Four Cheese
.
I don't see an easy way to solve this using your current approach.
But take a step back - do you really want to POST the price to your handling code? What if I edit the form in my browser and set the price to "1", or "0"? You should never trust data coming from the browser, and you have this data in your database already.
Do you really care about a pizza in the order if the quantity is 0? You can get rid of the checkbox, since entering a number in the quantity field controls whether or not they're getting that pizza.
Here's an alternative approach:
<?php while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC)) { ?>
<tr>
<td><?php echo $Row['pizzaID']; ?></td>
<td><?php echo $Row['pizzaName']; ?></td>
<td><?php echo $Row['pizzaPrice']; ?></td>
<td>
<!-- include the ids, we can refer to those for each quantity -->
<input type="hidden" name="ids[]" value="<?php echo $Row['pizzaID']; ?>"/>
<input type="number" name="Quantities[]" placeholder = "0"/>
</td>
</tr>
<?php } ?>
Now on your back end, you can do something like:
foreach ($_POST['Quantities'] as $key => $value) {
if (empty($value) || $value == 0) {
// wasn't ordered! Skip to the next.
continue;
}
$id = $_POST['ids'][$key];
// Now you know they want $value of pizza id $id. You can look
// up the price, name, etc, from your DB, same as you did to
// display them on the form in the first place.
}
Side note - it might just be copy-paste issues between your real code and your question here on SO, but the submit button should be inside the </form>
tag.
Upvotes: 1
Reputation: 2355
$values = array();
$quantities = array();
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
$quantities = $_POST['Quantities'];
$i=0;
foreach ($quantities as $q){
if($q){
$values[$i] = $values[$i].','.$q;
$i++;
}
}
below is my output
Array
(
[0] => 1,Hawa,150,23
[1] => 3,Four,300,33
)
Upvotes: 0
Reputation: 1320
Here your check box array indexing is different from quantity indexing so bcz of that you have to change the way of code:
on click check box you have to con-cat quantity with check box value like:
$(document).on('click','input[name=checkBoxName]',function()
{
if($(this).is(":checked")) //check if checkbox checked
{
var key = $(this).attr('data-cnt');
var qty = $("#qty"+key).val(); //return qty id value like qty1
$(this).val($(this).val()+','+qty);
}
else //check box not checked then remove last qty value
{
var text = $(this).val();
var resArray = text.split(",");
var poppedItem = resArray.pop();
var result = resArray.toString();
$(this).val(result);
}
});
before while loop declare cnt=0;
while()
{?>
<input type = "number" name = "Quantities[]" id="qty<?php echo $cnt?>" placeholder = "0"/>
<input type = "checkbox" name = "CheckBox[]" data-cnt="<?php echo $cnt?>" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/>
<?php }
when you post data then you will get :
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
var_dump($values);
you will get expected output.
Upvotes: 0