在mysql和php中,如何将每个数据添加到表的一列中?

jfgube3f  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(452)

我有一个列名称'销售'和销售列内有每个客户的销售清单。如何添加每个客户的所有销售额,然后回显表下的总销售额?

> ?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>";
        }
?>
mtb9vblg

mtb9vblg1#

对于mysql,可以使用sum group函数。
例如。 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>";

希望这能对你有所帮助。

cyej8jka

cyej8jka2#

运行 $sql = "SELECT *, SUM(sales) AS total_sale FROM 出售 GROUP BY 客户代码 "; 而不是 $sql = "SELECT * FROM sales";

krcsximq

krcsximq3#

您需要在循环外添加一个变量,并随着循环的每次迭代而递增

$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>";
}

相关问题