douke9545 2015-10-11 14:32
浏览 56
已采纳

PHP输出计算的SQL值

I am trying to add all the values in a single column from a table and then echo that value

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
            }
$sql = "SELECT sum(paid) as total_paid from users";
$result = $conn->query($sql);
echo $result;

But I end up getting this error:

Catchable fatal error: Object of class mysqli_result could not be converted to string in

Why and how can I fix?

  • 写回答

2条回答 默认 最新

  • dongpu4141 2015-10-11 15:16
    关注

    This is too long for a "comment".

    You need to loop over the results and use a while loop, rather than echoing the query which is why you're getting the present error.

    You also need to make sure that the paid column's type can be used to perform mathematical problems, such as int for instance (for example). If it's varchar, then you will need to cast it to an integer.

    References:

    Here is a procedural style method:

    $sql = "SELECT sum(paid) as total_paid from users";
    $result = $conn->query($sql);
    
    while ($row = mysqli_fetch_array($result)) {
        echo "Sum: " . $row['total_paid'];
    }
    

    or as an object-oriented method:

    while($row = $result->fetch_array()) {
            echo $sum = $row['total_paid'];
            }
    

    Sidenote:

    To calculate a row based on a user/id, add a WHERE clause in your query.

    I.e.: WHERE id='x'

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?