dongshi9407 2016-09-22 09:08
浏览 54
已采纳

如何在php预处理语句中显示值

I have the following query and I want to print the "total" I want to print the total like I print "num_rows" How can I do that ?

$stmt = $conn->prepare("SELECT SUM( total) AS total FROM money");
            $stmt->execute();
            $stmt->store_result();
            print $stmt->total;

my table structure are like this

id user monthly_pay total
1  Adam  1500       1500
2  Erik 1500       1500 
3  Mark  1500      1500
4 Gusta 1500       1500
5  Mike 1500       1500

I want to view the total "75000"

  • 写回答

2条回答 默认 最新

  • duanqiu9104 2016-09-22 09:45
    关注

    It's strictly not needed to use prepared statements when not dealing with user-input, but there's no disadvantage using it either (should you expand the query to deal with variables/user-input, the ground-work is already done!). This means for a static query like this, you can just use normal query() functions.

    However, using prepared statements like this, you need to bind the result and fetch it. Using $stmt->num_rows is going to trick you, as this will return the amount of rows returned by the query - which will only be 1. It will not return the result.

    The snippet below has been modified to use bind_result() and fetch(). This will prepare the query, bind the results to $sum and fetch it.

    $stmt = $conn->prepare("SELECT SUM( total) AS total FROM money");
    $stmt->execute();
    $stmt->bind_result($sum);
    $stmt->fetch();
    print "The sum is ".$sum;
    

    References

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?