I have a table that displays months(Jan through Dec) in a table as follows.
This table get the values from database and it is not fixed.
<table width="100%" style="font-size:9px">
<thead>
<tr>
<th colspan="14" style="text-align:center">Year: <?PHP echo $year?></th>
</tr>
<tr >
<th>Jan</th>
<th>Feb</th>
<th>Mar</th>
<th>Apr</th>
<th>May</th>
<th>Jun</th>
<th>Jul</th>
<th>Aug</th>
<th>Sep</th>
<th>Oct</th>
<th>Nov</th>
<th>Dec</th>
<th>Total</th>
</tr></thead><tbody>
<tr >
<?PHP
for ($i=1; $i<=12; $i++) {
$yearstart = $year."-".$i."-01";
$yearend = $year."-".$i."-31";
$sql="SELECT SUM(total) as totalsales_$i from salesorder where user_id=7 and created BETWEEN '$yearstart' AND '$yearend' ";
$res = $db->sql_query($sql);
$row = $db->sql_fetchrow($res);
$total = $total + $row['totalsales_'.$i];
?>
<td style="width: 96px; text-align:right">
<?PHP if ($row['totalsales_'.$i] !='' )
echo "$".number_format($row['totalsales_'.$i],2);
else
echo "<font color=#c2c2c2>$0.00</font>";?>
</td>
<?PHP //for ?>
<td style="text-align:right"><?PHP echo "$".number_format($total,2) ;?></td>
</tr>
</tbody></table>
OUTPUT:
Jan feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
$0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0
$0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0
$0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0 $0
...
...
But what I need is how to display the table vertically, as follows
2011 2012 2013 ...
Jan $0.00 $0.00 $0.00 $0.00
feb $0.00 $0.00 $0.00 $0.00
Mar $0.00 $0.00 $0.00 $0.00
Apr $0.00 $0.00 $0.00 $0.00
May $0.00 $0.00 $0.00 $0.00
Jun $0.00 $0.00 $0.00 $0.00
Jul $0.00 $0.00 $0.00 $0.00
Aug $0.00 $0.00 $0.00 $0.00
Sep $0.00 $0.00 $0.00 $0.00
Oct $0.00 $0.00 $0.00 $0.00
Nov $0.00 $0.00 $0.00 $0.00
Dec $0.00 $0.00 $0.00 $0.00
Total $0.00 $0.00 $0.00 $0.00
I tried a few different ways, but no luck. I wish I could show you some code here about what I tried, but I realy don’t have anthing to show.
Does anyone have any idea how to display this table vetically?
First of all , you may want to stop executing 12n queries and get all info with one go and power of aggregation mechanism in MySQL:
this will result in resultset like this:
So you will have sum for individual months in every row, sum for every year if
Mcolumn is null and sum for whole result in the last row (you can discard it, if you don’t need it)Now you have to create other array that will be easier to iterate while adding rows into your table. I would suggest it to look like this:
I don’t know what class are you using to interact with database, so let me assume there is some method that allows to fetch associative array from resultset
Finally you can present it in your table:
what needs to be corrected is to display month name and
Totalinstead of numbers in first column