MySQL SUM表中的所有值然后回显

时间:2012-12-09 05:20:44

标签: mysql

Table - Messages
+--------------------------------------------------------------------------------------------+
| msg_id | message | uid_fk | ip | created | uploads|
|  554  Blah....    35     ..  1355000068   0   |
|  555  Blah....    34     ..  1355002587   0   |
|  553  Blah....    34     ..  1354990968   0   |
+--------------------------------------------------------------------------------------------+

我要做的是获取uid_fk并将其全部加起来,然后能够使用php回显它。 uid_fk是另一个名为users的表中的用户uid,其中包含一些其他数据。我不确定如何通过获取他们的特定ID来将它们加在一起。

我从这开始,但我对MySQL数据库很新。

    public function Total_Posts($uid){
        $query          = mysql_query("SELECT uid_fk, sum(count) as sum from messages group by uid_fk");
        $num            = mysql_fetch_array($query);
        $return $num;
}

UPDATE: Working Version

    public function Total_Posts($uid){
        $messages       = mysql_query("SELECT * FROM messages WHERE uid_fk='$uid'");
        $numrows        = mysql_num_rows($messages);
        return $numrows;
    }

    <?php 
        $Total_Posts        = $Wall->Total_Posts($uid,$total);
    ?>

    <?php echo $Total_Posts; ?>

Seems to work great, thank you for all the help.

1 个答案:

答案 0 :(得分:0)

获取所需的所有元素:

$messages = mysql_query("SELECT * FROM Messages WHERE uid_fk='$uid'");

然后总结:

$sum=0;
while ($message = mysql_fetch_array($messages)){
    $sum += $message['uid_fk'];
}