使用pdo获取列中的值的总和

时间:2014-02-02 04:40:44

标签: php mysql sql database pdo

我想得到表all_nums中名为numbers的列中的所有值的总和,并将其存储到变量中。我在下面试过,但它找到了行数。

$dbh = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
$STH_SELECT = $dbh->query("SELECT count(*) FROM all_nums");
$sof = $STH_SELECT->fetchColumn(); 

2 个答案:

答案 0 :(得分:6)

要获得值的总和,您需要使用sum而不是count(*)。试试这个:

$STH_SELECT = $dbh->query("SELECT sum(numbers) FROM all_nums");

答案 1 :(得分:1)

公共函数GetBalance($ username){

        $query = $this->db->prepare("SELECT SUM(`balance`) FROM `users_table` WHERE `username` = ?" );
        $query->bindValue(1, $username);

        try{ $query->execute();   

        $total = $query->fetch(PDO::FETCH_NUM);
        $summ = $total[0]; // 0 is the first array. here array is only one.
        return $summ; 

        } catch(PDOException $e){
            die($e->getMessage());
        }   

}