Reputation: 1
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";
Upvotes: 0
Views: 120
Reputation: 166
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;
};
Upvotes: 1
Reputation: 477
$totalCost = 0;
while ($record = mysqli_fetch_array($recordSet, MYSQLI_ASSOC)) {
$cost = $record["productPrice"] * $record["quantity"];
$totalCost += $cost;
}
echo "$totalCost";
Upvotes: 1
Reputation: 3461
$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']
Upvotes: 0
Reputation: 11832
change
$cost = $productPrice * $quantity
into
$cost = $record["productPrice"] * $record["quantity"];
Upvotes: -1