Reputation: 25
Hi I need to get the sum of the database field sbstart. I changed the code to SUM(sbstart) but doesn't seems to be a valid move. How can I display the sum? Thanks.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'regional_data';
@ $db = mysqli_connect($host, $user, $pass, $db);
if(mysqli_connect_errno())
{
die('The connection to the database could not be established.');
}
$query = "SELECT SUM(sbstart) FROM newchk WHERE dist_chk ='$distUsr'";
$result = mysqli_query($db, $query);
while ($recS = mysqli_fetch_array($result)){
echo ($recS['sbstart']);
}
?>
Upvotes: 0
Views: 161
Reputation: 15981
Change
$query = "SELECT SUM(sbstart) FROM newchk WHERE dist_chk ='$distUsr'";
To (Use alias)
$query = "SELECT SUM(sbstart) as sub FROM newchk WHERE dist_chk ='$distUsr'";
Then
you doesn't need while loop because it return only one result.
$recS = mysqli_fetch_array($result);
echo $recS['sub'];
Upvotes: 2
Reputation: 1
Change
$query = "SELECT SUM(sbstart) FROM newchk WHERE dist_chk ='$distUsr'";
to
$query = "SELECT SUM(sbstart) AS sum FROM newchk WHERE dist_chk ='$distUsr'";
and change
echo ($recS['sbstart']);
to
echo ($recS['sum']);
Upvotes: 0
Reputation: 19539
You need to use either mysqli_fetch_assoc
instead of mysql_fetch_array
, or you need to do echo $recS[0]
.
Upvotes: 0