使用 pdo 按名称 SUM 行组 [英] SUM row group by name using pdo

查看:42
本文介绍了使用 pdo 按名称 SUM 行组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我更正以下代码.

Kindly help me correct following code.

<?php 
$sql = "SELECT SUM(quantity) from tblorders GROUP BY itemname" or die(mysql_error());
$query = $dbh->prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0) {
    foreach($results as $result):              
    ?>  
        <tr>
            <td> <?php echo htmlentities($cnt);?></td>
            <td><?php echo htmlentities($result->itemname);?></td>
            <td><?php echo htmlentities ($result->quantity);?></td>
       </tr>
    <?php 
    $cnt++;
    endforeach;
}?>

因为我无法按项目名称获得总和组.

as I am not able to get sum group by itemname.

推荐答案

尝试以下操作:

请注意,我已经为您修复了 sql.

Just notice that I have fixed sql for you.

<?php 
    $sql = "SELECT itemname, SUM(quantity) AS quantity from tblorders GROUP BY itemname";
    $query = $dbh -> prepare($sql);
    $query->execute();
    $results=$query->fetchAll(PDO::FETCH_OBJ);
    $cnt=1;
    if($query->rowCount() > 0) {
        foreach($results as $result) { ?>  

        <tr>
            <td> <?php echo htmlentities($cnt);?></td>
            <td><?php echo htmlentities($result->itemname);?></td>
            <td><?php echo htmlentities ($result->quantity);?></td>
        </tr>

<?php 
            $cnt++;
        } 
    }
?>

这篇关于使用 pdo 按名称 SUM 行组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆