简体   繁体   中英

How to add each data inside a column of a table in both mysql and PHP?

I have a column name 'sale' and inside the sale column there are list of sales per customer. how do i add all the sales of each customer and then echo the total sales under the table?

在此处输入图片说明

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

You need to add a variable outside of the loop and increment it with every iteration of the loop

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

For MySQL you can use SUM group function.

eg SELECT SUM(sales) as total FROM table_name;

And for PHP, you can do something like this:

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

Hope this can help you.

run

$sql = "SELECT *, SUM(sales) AS total_sale FROM sales GROUP BY customercode ";

instead of

$sql = "SELECT * FROM sales";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM