【问题标题】:getting sum of a column in php is not working在php中获取一列的总和不起作用
【发布时间】:2013-05-18 01:26:26
【问题描述】:

我正在尝试获取 php 内一列中的值的总和,但它根本不工作,而在 MySQL 中测试时查询工作正常这是代码(使用完整代码更新)

require('../_req/base.php');
$getCartQ = "select * from user_product inner join cart inner join products inner join users on user_product.User_ID = cart.User_ID and user_product.User_ID = users.User_ID group by cart.User_ID";
$getCartR = mysql_query($getCartQ);
?> <table align="center" width="1271" border="0" cellpadding="0" cellspacing="0">

 <?php
 while($cartRow = mysql_fetch_array($getCartR)){

     $sumQ = "select SUM(Total) as total from user_product where Status = 'active' and user_product.User_ID = '$cartRow[User_ID]'";
     $sumR = mysql_query($sumQ) or die(mysql_error());
     $sumRow = mysql_fetch_assoc($sumR);
     $cost = $sumRow['total'];
    ?>
    <tr>
    <td><?php echo $cartRow['Full_Name'] ?></td>
    <td><?php echo $cartRow['State']; ?></td>
    <td><?php echo $cost; ?></td>
    </tr>
    <?php 
 }
 ?>
 </table>
 <?php
mysql_close($connect);

当我尝试回显 $cost 时,我什么也没得到,只是一个空格,该代码有什么问题?

【问题讨论】:

  • 你不应该使用 mysql api for php。使用 MySQLi 或 PDO。自 PHP 5.5.0 起已弃用
  • 只需在查询 $sumQ 之前回显连接对象并检查它是否存在。
  • 应该有一些内置的魔术函数自动发布“不要使用 mysql_*,使用 SQLi/PDO”的口头禅,作为对代码块中包含“mysql_query”的任何问题的自动评论。想想人们每天花在写它上的所有工时。

标签: php mysql sum


【解决方案1】:
 user_product.User_ID = '$getCartR[User_ID]'";

 user_product.User_ID = '{$getCartR['User_ID']}'";

【讨论】:

  • 我也正要说这个……下次把所有代码一次性放好:)
【解决方案2】:

echo mysql_error();

最后告诉我它显示了什么。你会在那里得到答案

【讨论】:

  • 按照你的建议写的
  • 提供的资源不是有效的 MySQL-Link 资源
  • 在运行查询之前,您是否使用mysql_connect('host','user','pass');mysql_select_db('dbname'); 建立了数据库连接?
  • 为什么当 te 查询在 MySQL (phpmyadmin) 中工作时出现此错误?
  • 是的,确定连接已经开始,并且在获取其他数据之前还有另一个查询
【解决方案3】:

我刚刚删除了缓存,一切正常我不知道这与缓存有什么关系谢谢大家的帮助我很感激

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多