StressedStudent StressedStudent - 3 months ago 14
MySQL Question

How can i print how many Id's i have in my database in php

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.

Answer

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