Edward144
Edward144

Reputation: 493

Add Numbers Together From Mysql Database in PHP

I need to add some numbers together that are being pulled from a MySQL table to get a total value.

Currently the issue I have is the numbers being added to the end of a string instead.

e.g:

1,2,3,4 becomes 1234 instead of 10

Here is what I am using to get the numbers from the database:

$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");

while($row = mysqli_fetch_assoc($count)) {
    $total .= $row['Quantity'];
    //I Have also tried
    $total .= (int)$row['Quantity'];
}

echo $total;

The Quantity Column is set to be an INT in the table so I would have expected it to add together automatically. What am I doing wrong?

Upvotes: 1

Views: 3203

Answers (1)

Twinfriends
Twinfriends

Reputation: 1987

You should probably look at the difference between .= and +=

By adding a . in front of = you concatenate - You add the value ad the end of the variable.

If you would use a + in front of your = you would actually get the result you want.

$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
$total = 0;
while($row = mysqli_fetch_assoc($count)) {
    $total += $row['Quantity'];
}
echo $total;

http://php.net/manual/en/language.operators.string.php

Upvotes: 4

Related Questions