我在表格中有一个列,我想加起来并返回总和。我有一个循环,但它不起作用。
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
答案 0 :(得分:98)
您可以在MySQL查询中完全处理它:
SELECT SUM(column_name) FROM table_name;
在PHP代码中,试试这个:
$result = mysql_query('SELECT SUM(value) AS value_sum FROM codes');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
使用PDO(不推荐使用mysql_query
)
$stmt = $handler->prepare("SELECT SUM(value) AS value_sum FROM codes");
$stmt->execute();
$row = $handler->fetchAll(PDO::FETCH_OBJ);
$sum = $row->value_sum;
答案 1 :(得分:9)
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
答案 2 :(得分:5)
试试这个:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
答案 3 :(得分:2)
$row['Value']
可能是一个字符串。尝试使用intval($row['Value'])
。
另外,请确保在循环前设置$sum = 0
。
或者,更好的是,将SUM(Value) AS Val_Sum
添加到SQL查询中。
答案 4 :(得分:2)
我已经更换了您的代码并且运行良好
$sum=0;
while ($row = mysql_fetch_assoc($result)){
$value = $row['Value'];
$sum += $value;
}
echo $sum;
答案 5 :(得分:2)
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
答案 6 :(得分:1)
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;
答案 7 :(得分:1)
MySQL 5.6(LAMP)。 column_value是您要添加的列。 table_name是表。
方法#1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
方法#2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
方法#3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
方法#4:折旧(不使用)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
答案 8 :(得分:0)
使用PHP MYSQL获取特定行值的总和
"SELECT SUM(filed_name) from table_name"
答案 9 :(得分:0)
我们要添加日期“ 09-10-2018”中的“ duration_sec”列的所有值,并且仅添加状态“ off”
下面是sql查询:
$sql_qry="SELECT SUM(duration_sec) AS count FROM tbl_npt WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
while($record = $duration->fetch_array()){
$total = $record['count'];
}
echo $total