2016-10-04 46 views
0

我有一個腳本,我想將它放在儀表板上。 SQL在while中正常工作和分組,並且正確顯示在儀表板中。但是我也想要顯示數量。在SQL組中計數行

因此,如果SQL是分組的,我如何計算它返回的行數,以便我可以將每個行的數據傳回到我的表中。這是我的代碼。

<?php 
    $servername = "localhost"; 
    $username = "root"; 
    $password = "root"; 
    $dbname = "dbname"; 
    $custid = $row['CustomerID']; 
    // Create connection 
    $conn = new mysqli($servername, $username, $password, $dbname); 
    // Check connection 
    if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
    } 
    $sql1 = "SELECT * FROM stock 
      JOIN hardware ON stock.HardwareID = hardware.HardwareID 
      WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID"; 
    $result1 = $conn->query($sql1); 
    if ($result1->num_rows > 0) { 
     // output data of each row 
     while($row1 = $result1->fetch_assoc()) { 
      echo "<tr>"; 
      echo "<td>".$row1['Hardware']."</td>"; 
      echo "<td></td>"; 
      echo "</tr>"; 
     } 
    } 
?> 

所以,目標是使該行

echo "<td></td>"; 

有它的一個變量,它顯示的是被分組的每一行的數量。

+0

的MySQL或* SQL Server?選擇標籤時請小心。 – DavidG

+0

對不起,解決了這個問題。 – Legend1989

回答

2

您可以使用此查詢,按查詢組有權選擇和提供聚集,在這裏,我已經提供了計數,如果你需要一些適當的列可以相應地改變它...

  <?php 
       $servername = "localhost"; 
       $username = "root"; 
       $password = "root"; 
       $dbname = "dbname"; 

       $custid = $row['CustomerID']; 

       // Create connection 
       $conn = new mysqli($servername, $username, $password, $dbname); 
       // Check connection 
       if ($conn->connect_error) { 
        die("Connection failed: " . $conn->connect_error); 
       } 
       $sql1 = "SELECT stock.Hardwareid, count(*) as CountHardware FROM stock 
       JOIN hardware ON stock.HardwareID = hardware.HardwareID 
       WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID"; 
        $result1 = $conn->query($sql1); 

       if ($result1->num_rows > 0) { 
        // output data of each row 
        while($row1 = $result1->fetch_assoc()) { 
         echo "<tr>"; 
         echo "<td>".$row1['Hardware']."</td>"; 
         echo "<td></td>"; 
         echo "</tr>"; 
        } 
       } 
      ?> 
+0

這工作得很好。我只是需要做出一個改變。$ SQL1 =「SELECT stock.Hardwareid,hardware.Hardware,COUNT(*)作爲CountHardware現貨 \t \t \t \t \t \t \t \t \t JOIN硬件ON stock.HardwareID = hardware.HardwareID \t \t \t \t \t \t \t \t WHERE stock.CustomerID = $ custid GROUP BY stock.HardwareID「;但會接受這個答案。謝謝 – Legend1989