[英]How to add each data inside a column of a table in both mysql and PHP?
我有一個名為“ sale”的列,在sales列中有每個客戶的銷售清單。 如何將每個客戶的所有銷售額相加,然后在表下顯示總銷售額?
> ?php
include('conn.php');
$sql = "SELECT * FROM sales";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
if($count>0)
{
echo "<html><head></head><body><table border=1>
<th>CODE</th>
<th>Employee Name</th>
<th>Customer</th>
<th>Sales</th>";
while($row = mysqli_fetch_assoc($result))
{
echo"<tr>";
echo"<td>".$row['empcode']."</td>
<td>".$row['fullname']."</td>
<td>".$row['customercode']."</td>
<td>".$row['sales']."</td></tr>";
}
echo"</table>";
}
?>
您需要在循環外添加一個變量,並在每次循環中將其遞增
$totalSales = 0;
if($count>0)
{
echo "<html><head></head><body><table border=1>
<th>CODE</th>
<th>Employee Name</th>
<th>Customer</th>
<th>Sales</th>";
while($row = mysqli_fetch_assoc($result))
{
echo"<tr>";
echo"<td>".$row['empcode']."</td>
<td>".$row['fullname']."</td>
<td>".$row['customercode']."</td>
<td>".$row['sales']."</td></tr>";
$totalSales += $row['sales'];
}
echo"</table>";
}
對於MySQL,您可以使用SUM組功能。
例如SELECT SUM(sales) as total FROM table_name;
對於PHP,您可以執行以下操作:
$total = 0;
while($row = mysqli_fetch_assoc($result))
{
$total += $row['sales'];
echo"<tr>";
echo"<td>".$row['empcode']."</td>
<td>".$row['fullname']."</td>
<td>".$row['customercode']."</td>
<td>".$row['sales']."</td></tr>";
}
// Print total at the end
echo "<tr>";
echo "<td colspan='3'>Total</td>";
echo "<td>".$total."</td>";
echo "</tr>";
希望這可以幫到你。
跑
$sql = "SELECT *, SUM(sales) AS total_sale FROM
sales GROUP BY
客戶代碼";
代替
$sql = "SELECT * FROM sales";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.