'Shopping cart total concept
<?php
include 'Conn.php';
$sql="SELECT * FROM `cart` where active=0";
$result=$conn->query($sql);
if($result){
while ($row = $result->fetch_assoc()){
$counter=1;
$id=$row['id'];
$productid=$row['productid'];
$PRICE=$row['PRICE'];
$total=$row['PRICE'];
echo'
<tr>
<td>'.$counter.'</td>
<td>'.$productid.'</td>
<td>'.$PRICE.'</td>
<td><button type="button" class="btn btn-danger" ><a href="cartdelete.php?deleteid='.$id.'"class="text-light">REMOVE</a></button></td>
<td>'.$total.'</td>
</tr>';
}
}
?>
I Need A help for Total how can I total the amount I have tried the total +=$PRICE this piece of code
Solution 1:[1]
Try this
<?php
include 'Conn.php';
$sql="SELECT * FROM `cart` where active=0";
$result=$conn->query($sql);
//initializing total to 0
$total = 0;
if($result){
while ($row = $result->fetch_assoc()){
$counter=1;
$id=$row['id'];
$productid=$row['productid'];
$PRICE=$row['PRICE'];
//adding product price to total amount
$total += (double)$row['PRICE'];
echo'
<tr>
<td>'.$counter.'</td>
<td>'.$productid.'</td>
<td>'.$PRICE.'</td>
<td><button type="button" class="btn btn-danger" ><a href="cartdelete.php?deleteid='.$id.'"class="text-light">REMOVE</a></button></td>
</tr>
';
}
//displaying total, you can show wherever you like
echo 'Total: '.$total;
}
?>
I have also added comment on the code, so that you could get an idea, about what you are doing.
Solution 2:[2]
function get_numerics ($str) {
preg_match_all('/\d+/', $str, $matches);
return $matches[0];
}
<table>
<thead>
<tr>
<th>N°</th>
<th>Product ID</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include 'Conn.php';
$sql="SELECT * FROM `cart` where active=0";
$result=$conn->query($sql);
//initializing total to 0
$total = 0;
if($result){
while ($row = $result->fetch_assoc()){
$counter =1;
$id =$row['id'];
$product_id =$row['productid']; //Change $productid to $product_id, by adapting snake case
$price =$row['PRICE']; //Change $PRICE to $price ,variable as upcase is for constant varaible unique
$total +=get_numerics($row['PRICE']); //Adding product price to total amount
echo'
<tr>
<td>'.$counter.'</td>
<td>'.$product_id.'</td>
<td>'.$price.'</td>
<td><button type="button" class="btn btn-danger" ><a href="cartdelete.php?deleteid='.$id.'"class="text-light">REMOVE</a></button></td>
</tr>';
$counter ++; //product type counter
}
}
?>
<!-- Style improvement for more information check css attribute guild -->
<tr><td style='colspan:4;text-align: right;'>Total : <?php echo $total ?> </td></tr>
</tbody>
</table>
try this out , you will get the total price at the end the table with an individuel row
and also dont forget to change the table header
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
