PHP Sum of Mysql行值

时间:2014-03-05 06:42:24

标签: php mysql add

figure 1. sum all value of money   
    id  date           name     money //sample items only
    1   March 5 2014   matt      50 //records to add
    2   March 5 2014   john      10 //records to add
    3   March 2 2014   matt      50 //records to add

figure 2. sum all value of money when search matt
    id  date           name     money //sample items only
    1   March 5 2014   matt      50 //records to add
    2   March 5 2014   john      10
    3   March 2 2014   matt      50 //records to add

大家好你能帮我吗?我不知道代码如何在我的sql数据库中添加行值。(见上面的示例)

我有这个代码,它将计算我有多少记录

<input type="text" name="namesearch" size="5"  tabindex="1" />

<input type="submit" name='click' value='Search' />


if(isset($_POST['click'])){


    $name= $_POST['namesearch'];
    $query = "SELECT COUNT(*) AS total FROM table WHERE name='$name'"; 
    $result = mysql_query($query); 
    $values = mysql_fetch_assoc($result); 
    $num_item= $values['total']; 
    echo "Number of Records Found # ".$num_item;

3 个答案:

答案 0 :(得分:3)

将此作为查询

$query = "SELECT COUNT(*) AS total, SUM(money) AS total_money FROM table WHERE name='$name'"; 

使用它来查看结果

$num_item = $values['total']; 
$total_value = $values['total_money'];
echo "Number of Records Found # ".$num_item;
echo "Total Money ".$total_value

答案 1 :(得分:0)

由于我的MySQL服务器在操作系统升级后丢失,所以不要相信语法(lol)。试试这个:

SELECT COUNT(*), SUM(`money`) AS `total_money` FROM `my_table` GROUP BY `name`;

这应该(?)给你每个名字的行数和它的总金额。

答案 2 :(得分:0)

使用MySQL SUM Function

SELECT SUM(money) AS total FROM table WHERE name='$name'