I have a column in a table that I would like to add u开发者_如何学Gop and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query
is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #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";
Method #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";
Method #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";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value']
is probably a string. Try using intval($row['Value'])
.
Also, make sure you set $sum = 0
before the loop.
Or, better yet, add SUM(Value) AS Val_Sum
to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;
精彩评论