Как добавить все данные внутри столбца таблицы в MySQL и PHP? - PullRequest
0 голосов
/ 30 августа 2018

У меня есть имя столбца «продажа», а внутри столбца продажи есть список продаж на одного клиента. Как добавить все продажи каждого клиента, а затем отобразить общие продажи под таблицей?

enter image description here

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

Ответы [ 3 ]

0 голосов
/ 30 августа 2018

Для 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>";

Надеюсь, это поможет вам.

0 голосов
/ 30 августа 2018

пробег

$sql = "SELECT *, SUM(sales) AS total_sale FROM продажа GROUP BY customercode ";

вместо

$sql = "SELECT * FROM sales";

0 голосов
/ 30 августа 2018

Вам нужно добавить переменную вне цикла и увеличивать ее с каждой итерацией цикла

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