如何将MYSQL COUNT(*)语句的结果返回到HTML表中的单独列中

问题描述:

How to return result of MYSQL COUNT() Statement into separate columns within a HTML Table*

MYSQL - PHP

$sql= mysql_query("select count(*), shop_order_action from shop_orders o
                  WHERE shop_order_action IN ('Sale', 'Transfer', 'Delivery', 'Return')
                  AND shop_order_day = '28' AND shop_order_month = '08' AND shop_order_year = '2014'
                  AND shop_order_location = 'Bawtry'
                  GROUP BY FIELD (shop_order_action, 'Sale', 'Transfer', 'Delivery', 'Return')");


while ($row=mysql_fetch_row($sql)) {
echo "<pre>";
print_r($row);
echo "</pre>";

}

RESULT OF PRINT_R

Array
(
    [0] => 8
    [1] => Sale
)
Array
(
    [0] => 2
    [1] => Transfer
)
Array
(
    [0] => 1
    [1] => Return
)

TABLE

Shop Action    Count       

SALE           <? echo $row[0] ?> 
TRANSFER       <? echo $row[0] ?> 
DELIVERY       <? echo $row[0] ?>            
RETURN         <? echo $row[0] ?>

So I need to return the correct row value i.e. Sale, Transfer ... etc in the corresponding column within the table.

I could iterate through the results with a while loop, however, I'm having trouble figuring out how to structure the loop so that it prints out each row in order within the while loop without having to go to the top of the loop.

Maybe I should use a while loop and the continue condition, so that every time $row[0] is echoed it returns the next row.

I came up with a solution which may not be optimal but it performs as required:

Solution

    $sql= mysql_query("select count(*), shop_order_action from shop_orders o
                  WHERE shop_order_action IN ('Sale', 'Transfer', 'Delivery', 'Return')
                  AND shop_order_day = '".$d."' AND shop_order_month = '".$m."' AND shop_order_year = '".$y."'
                  AND shop_order_location = 'Bawtry'
                  GROUP BY FIELD (shop_order_action, 'Sale', 'Transfer', 'Delivery', 'Return')");


while ($result=mysql_fetch_row($sql)) {

  if ($result[1] == 'Sale') { $sale = $result[0]; } 
  if ($result[1] == 'Transfer') { $transfer = $result[0]; } 
  if ($result[1] == 'Delivery') { $delivery = $result[0]; } 
  if ($result[1] == 'Return') { $return = $result[0]; } 

}
  if (isset($sale)) { echo $sale; }
  echo '<br />';
  if (isset($transfer)) { echo $transfer; }
  echo '<br />';

  etc ...

The code within the while loop stores each action value as a variable which can be called outside of the loop.