Question

so I have a while loop in php that I am pulling each record out of the mysql database, which works just fine, but what I want to do now is add the results of the column QTY together to get a total amount, but im not sure how to go about adding each of the results together as each time the while loop loops, it wipes the last loop.

For example if I have the following records :

ID  QTY   NAME
1    2    BOX1
2    54   BOX2
3    21   BOX6

When I echo them out in the while loop I get pretty much as they are above. What I want to do is add the QTY to a total each time, so I can get a QTY total and have it available to use as $totalQTY .

    $sql = <<<SQL
    SELECT * FROM `orders` WHERE `orderid` = '$view' AND `isline` = 'no'
    SQL;
    if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
    while($row = $result->fetch_assoc()){
    echo '<h2>Order Id : '.$row['orderid'].'</h2>';
    echo '<p><strong>Customer Order Number : '.$row['customerordernumber'].'</strong></p>';
    echo '<p><strong>Order Date :</strong> '.date("d/m/Y H:i:s", strtotime($row["orderdatetime"])).'</p>';
    echo '<p><strong>Order Notes :</strong> '.$row['ordernotes'].'</p>';
    echo '<p><strong>Label Type :</strong> '.$row['labeltype'].'</p>';
    echo '<p><strong>Trolley Type :</strong> '.$row['trolleytype'].'</p>';
    echo '<p><strong>Deliver By :</strong> '.$row['deliverby'].'</p>';
    echo '<p><strong>Ordered Items : </strong></p>';
    }
Was it helpful?

Solution

$sql = <<<SQL
SELECT * FROM `orders` WHERE `orderid` = '$view' AND `isline` = 'no'
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' .$db->error . ']');}
$totalqty=0; // add this
while($row = $result->fetch_assoc()){
echo '<h2>Order Id : '.$row['orderid'].'</h2>';
echo '<p><strong>Customer Order Number : '.$row['customerordernumber'].'</strong></p>';
echo '<p><strong>Order Date :</strong> '.date("d/m/Y H:i:s", strtotime($row["orderdatetime"])).'</p>';
echo '<p><strong>Order Notes :</strong> '.$row['ordernotes'].'</p>';
echo '<p><strong>Label Type :</strong> '.$row['labeltype'].'</p>';
echo '<p><strong>Trolley Type :</strong> '.$row['trolleytype'].'</p>';
echo '<p><strong>Deliver By :</strong> '.$row['deliverby'].'</p>';
echo '<p><strong>Ordered Items : </strong></p>';
$totalqty+=intval($row['QTY??']); //your field value must be changed add this
}

Just add one counter variable as above :)

OTHER TIPS

Create a variable outside the loop, and increment it:

$count=0
while($row = $result->fetch_assoc()){
     $count+=$row['quantity'];
}
echo $count;

Just do exactly what you wrote:

$totalQTY = 0
while (....) {
   //...all your code....
   $totalQTY += $row['QTY']; // you didn't give the name of the column
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top