Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I have a table in mySQL that holds sale records which have customerID, productPrice, and quantity. I need to get the cost from each row, and then compile that into a totalCost. I need to use a while loop (assignment instructions) to do so, and so far I have not had any luck. Here is where I am at now, any help is appreciated

while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $productPrice * $quantity
    $totalCost = $totalCost + $cost
};
echo "$totalCost";
share|improve this question

4 Answers 4

This is more of a comment , but am not cool enough to write one, try putting your $totalcost variable out side of your while loop, that way its value won't be overwritten with each iteration.

$totalcost=0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
$cost = $record['productPrice'] * $record['quantity'];
$totalCost = $totalCost + $cost;
};
share|improve this answer
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $record["productPrice"] * $record["quantity"];
    $totalCost += $cost;
}
echo "$totalCost";
share|improve this answer
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $record['productPrice'] * $record['quantity'];
    $totalCost += $cost
}
echo "$totalCost";

You first need to declare $totalCost or else you'll get an undefined error, you don't need to add semi-colons to curly brackets when ending them, and also when you're pulling information using $record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC) you need to access the information as array keys so the price would be $record['price']

share|improve this answer

change

$cost = $productPrice * $quantity

into

$cost = $record["productPrice"] * $record["quantity"];
share|improve this answer
    
Why the -1? I'm really curious. –  nl-x Dec 11 '13 at 22:12
    
yeah me too ! why? –  Robert Brooks Dec 11 '13 at 22:15
    
guess someone didn't like me beating him to the punch. –  nl-x Dec 11 '13 at 22:16
    
I see your answer doesn't entirely solve the problem to the question, but still a valid point. –  Robert Brooks Dec 11 '13 at 22:17
    
No, it does entirely solve the problem. Indeed, not declaring the $productPrice outside the loop will cause a notice, but it will work. The price will add up, and the echo will show. –  nl-x Dec 11 '13 at 22:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.