Single Result From SUM With MySQLi

后端 未结 2 1774
长情又很酷
长情又很酷 2020-12-07 06:08

Looked all over. Can\'t find an answer. PHP docs not clear (to me).

I\'m doing a simple MySQL sum through mysqli->query. How can I get the result w

相关标签:
2条回答
  • 2020-12-07 06:46

    It's best if you used an alias for your SUM:

    SELECT SUM(`field`) as `sum` FROM `table_name`
    

    And then, you'll be able to fetch the result normally by accessing the first result row's $row['sum'].

    0 讨论(0)
  • 2020-12-07 06:52

    Whatever is given in the SELECT statement to mysqli_query is going to return a mysql_result type if the query was successful. So if you have a SELECT statement such as:

    SELECT sum(field) FROM table1
    

    you still need to fetch the row with the result, and the value of the sum() function will be the only entry in the row array:

    $res = mysqli_query($dbh,'SELECT sum(field) FROM table1');
    $row = mysqli_fetch_row($res);
    $sum = $row[0];
    
    0 讨论(0)
提交回复
热议问题