-1

I don't understand why this isn't working and i don't know how to fix it:

    $sum=0;
    $queryone="SELECT SUM(ID) FROM seriestwo";
    $result = mysqli_query($link,$queryone);
    $row = mysqli_fetch_array($result, MYSQLI_NUM);

    while($row = $result->fetch_assoc()){

        $sum = $sum + 1;

    }
echo $sum

it always prints 0.

  • 1
    You're using the wrong logic. You're doing `while($row...` but not doing anything "with" `$row`. You should also be counting not summing, unless that's what you want, I don't know. – Funk Forty Niner Aug 28 '16 at 18:45
  • i updated it, i am summing, i want to show how many entries there are in the database, for example id 1 id 2 id 3 it willl print 3 ids – StressedStudent Aug 28 '16 at 18:50
  • I noticed the other answer made an edit to their answer using an alias where I did not see it when I posted my own answer. You have a choice now. – Funk Forty Niner Aug 28 '16 at 19:15
  • Ok, I noticed you accepted their answer. I'm glad you got your solution then. I was away for a bit, which explains my late answer. "Hunger" got the best of me ;-) – Funk Forty Niner Aug 28 '16 at 19:17

2 Answers2

2

What you are doing is wrong because the $result stores only 1 row, that is the sum of ID. You can try two things:

Method 1: Use COUNT() in mysqli. Check MySQL Reference

For eg. check: select count(*) from table of mysql in php

$queryone="SELECT COUNT(ID) as total FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_assoc($result, MYSQLI_NUM);
echo $row['total'];

Method 2: Use this code:

$sum=0;
$queryone="SELECT `ID` FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_array($result, MYSQLI_NUM);

while($row = $result->fetch_assoc()){
   $sum = $sum + 1;
}
echo $sum;


Which Method to Use

The first method is the one you should be using right now, in this case. You can use second when you want to add extra things, like print every ID

Community
  • 1
  • 1
frunkad
  • 2,433
  • 1
  • 23
  • 35
1

You may be overthinking this.

It's as simple as the following and using an alias while using only 3 lines of code:

$query = $link->query("SELECT SUM(`ID`) as `total` FROM seriestwo");
$row = $query->fetch_assoc();
echo $row['total'];
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Though your approach is right, I think the user wants to count the number of ids and not the sum. I am not sure but. – frunkad Aug 28 '16 at 19:33
  • @DarshanJain TBH, after seeing their comment about *"for example id 1 id 2 id 3 it willl print 3 ids"* in comments above, had second thoughts in regards to the answer I gave here, where I should have used a different approach. Don't get me wrong, I don't want to take away from your answer. They also wrote *"i updated it, i am summing"*. – Funk Forty Niner Aug 28 '16 at 19:39