在PHP中获取SUM以获取数据库值[关闭]

How could I get sum value in php file

$a = mysql_query('SELECT d.name, d.idnumber, d.days FROM users d');
while($row = mysql_fetch_array($a))
{
   $idnumber = $row['idnumber'];
   $days     = $row['days'];
   echo $array_sum($days); 
}

I need to sum the variable that I got from database in php file, but not as SUM in the query. In my database I Have 3 rows i.e., 3, 10 and 1. So I need 14 as sum

$sum = 0;
$a = mysql_query('SELECT d.name, d.idnumber, d.days FROM users d');
while($row = mysql_fetch_array($a))
{
   $idnumber = $row['idnumber'];
   $days     = $row['days'];
   $sum     += intval($days);
}
echo $sum;
$sum = 0
while(...){
   ....
   $sum += $days;
   echo $sum;
}

Another option, if you find yourself needing to do things like this often, is to transpose the results, which will then let you easily sum the column you want. I wrote in detail about doing this in a blog post. The transpose function is also pasted below if you don't want to have to click through:

function transpose($array) {
    if (!is_array($array) || empty($array)) {
        return array();
    }
    else {
        foreach ($array as $row_key => $row) {
            if (is_array($row) && !empty($row)) { //check to see if there is a second dimension
                foreach ($row as $column_key => $element) {
                    $transposed_array[$column_key][$row_key] = $element;
                }
            }
            else {
                $transposed_array[0][$row_key] = $row;
            }
        }
        return $transposed_array;
    }
}

Applying this to the code you posted in your question, you get

$a = mysql_query('SELECT d.name, d.idnumber, d.days FROM users d');
$rows = array();
while($row = mysql_fetch_assoc($a)) {
    $rows[] = $row;
}
$transposed_results = transpose($rows);
echo array_sum($transposed_results['days']);

Using this technique has other benefits such as allowing you to easily foreach through the values of a column, or to run a more complex array_map callback on a column's values.