简体   繁体   中英

MySQL SUM all values from table then echo

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   |
+--------------------------------------------------------------------------------------------+

What I'm trying to do is get uid_fk and sum it all up, and then be able to echo it using php. The uid_fk is the user uid in another table called users with some other data. I'm not sure at all how to sum it both together by getting their specific ID's.

I started with this but I'm pretty new with MySQL databases.

    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.

get all the elements you need:

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

then sum:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM