猿问

使用 php 和 mysql 计算总值而不是行

我正在尝试计算收集的令牌总数,而不是mysql数据库中的记录数。虽然我已经将SUM函数放在查询中,但它仍然计算no。行数。


<?php 

   $conn = mysqli_connect(server, dbuser, dbpw, db);


   $query = " SELECT SUM(nooftokensused) FROM bidding WHERE biddedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-01-01') GROUP BY biddingid";

   $query_run = mysqli_query($conn, $query);


   $row = mysqli_num_rows($query_run); 


   echo '<h1>'.$row.'</h1>';

?>


慕森王
浏览 104回答 2
2回答

繁花如伊

我已经在我的代码中添加了注释。此外,您正在使用 ,您尚未将它们声明为带有符号的变量。mysqli_connect(server, dbuser, dbpw, db)$<?php&nbsp; &nbsp; //Make connection with DB&nbsp; &nbsp; $con = mysqli_connect($server, $dbuser, $dbpw, $db);&nbsp; &nbsp; if (mysqli_connect_errno()) {&nbsp; &nbsp; &nbsp; echo "Failed to connect to MySQL: " . mysqli_connect_error();&nbsp; &nbsp; &nbsp; exit();&nbsp; &nbsp; }&nbsp; &nbsp; $sql = "SELECT SUM(nooftokensused) as summ FROM bidding WHERE biddedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-01-01') GROUP BY biddingid";&nbsp; &nbsp; $result = mysqli_query($con, $sql);&nbsp; &nbsp; if(mysqli_num_rows($result)>0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Associative array&nbsp; &nbsp; &nbsp; &nbsp; $row = mysqli_fetch_assoc($result);&nbsp; &nbsp; &nbsp; &nbsp; echo $row["summ"];&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo 0;&nbsp; &nbsp; }&nbsp; &nbsp; // Free result set&nbsp; &nbsp; mysqli_free_result($result);&nbsp; &nbsp; mysqli_close($con);&nbsp; &nbsp; ?>

慕侠2389804

使用 mysqli_fetch_assoc() 而不是 mysqli_num_rows()。<?php&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $conn = mysqli_connect(server, dbuser, dbpw, db);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query = " SELECT SUM(value_sum) AS nooftokensused FROM bidding WHERE biddedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-01-01') GROUP BY biddingid";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query_run = mysqli_query($conn, $query);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $row = mysqli_fetch_assoc($query_run);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<h1>'.$row['nooftokensused'].'</h1>';&nbsp;?>
随时随地看视频慕课网APP
我要回答