1

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?

5
  • 2
    you used a dot instead of a plus + sign. Commented Feb 8, 2018 at 12:15
  • this is a typo question Commented Feb 8, 2018 at 12:18
  • 4
    Why not do SELECT SUM(QUANTITY) AS QUANTITY FROM Table as your database query? Commented Feb 8, 2018 at 12:18
  • @FunkFortyNiner I tried that and it gave the error Undefined Variable $total. I've now realised I should have created the variable initially as 0. So it works, thanks. Commented Feb 8, 2018 at 12:21
  • you could have first assigned it as $total = ""; then the rest with the plus sign ;-) that is but one way to do it. That's why you got the undefined notice. Commented Feb 8, 2018 at 12:21

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.