0

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";

4 Answers 4

1
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
    $cost = $record["productPrice"] * $record["quantity"];
    $totalCost += $cost;
}
echo "$totalCost";
Sign up to request clarification or add additional context in comments.

Comments

1

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;
};

Comments

0
$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']

Comments

-1

change

$cost = $productPrice * $quantity

into

$cost = $record["productPrice"] * $record["quantity"];

5 Comments

Why the -1? I'm really curious.
guess someone didn't like me beating him to the punch.
I see your answer doesn't entirely solve the problem to the question, but still a valid point.
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.
Yeah your right it will add up. But the persitance o the error message isn't a 100% solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.