Grafity Grafity - 2 months ago 7
PHP Question

foreach for php merging and adding the total amount in php

So guys I have a php code here:

<?php foreach($posts as $post){ ?>
<?php $totamount = ($post->price) * ($post->qty); ?>
<table>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Price<th>
<th>Total</th>
</tr>
<tr>
<td><div class="name"><?php echo $post->name; ?></div></td>
<td><div class="qty"><?php echo $post->qty; ?></div></td>
<td><div class="price"><?php echo $post->price; ?></div></td>
<td><div class="totamount"><?php echo $totamount; ?></div></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<div class="client"><?php echo $post->firstname; ?> <?php echo $post->lastname; ?></div>
<?php } ?>


If the client reserves one product it is good, but when the client adds new product, the receipt would look like this:

Item Name Quantity Price Total
gown 2 7.50 15

clients name

Item Name Quantity Price Total
bridal 1 5.00 5

clients name


Suddenly this became a loop, you can see that the is looping and also the client name, I want it to be like this:

Item Name Quantity Price Total
gown 2 7.50 15
bridal 1 5.00 5

TOTAL AMOUNT: 20

clients name


And also, how can i get the TOTAL AMOUNT without using SQL because Total is not in the database! how will I do everything right?

Answer

Put in the loop only the <tr> with the product info:

<table>
    <tr>
        <th>Item Name</th>
        <th>Quantity</th>
        <th>Price<th>
        <th>Total</th>
    </tr>
    <?php foreach($posts as $post){ ?>
        <?php $totamount = ($post->price) * ($post->qty); 
        $orderTotal += $totamount;
    ?>
        <tr>
            <td><div class="name"><?php echo $post->name; ?></div></td>
            <td><div class="qty"><?php echo $post->qty; ?></div></td>
            <td><div class="price"><?php echo $post->price; ?></div></td>
            <td><div class="totamount"><?php echo $totamount; ?></div></td>
        </tr>
    <?php } ?>
</table>
<div class="total"><?=$orderTotal?></div>
<div class="client"><?php echo $post->firstname; ?> <?php echo $post->lastname; ?></div>
Comments