Kris Edwards
Kris Edwards

Reputation: 35

Creating table with rowspan php

I have been trying to figure out how to create the below table in php that i then include on another page, table i want to create is:

What I want to display

I have been using the below code which works on the first rowspan rows but not any others:

<?php
    $tbl1 = sqlsrv_query($connys,"

    select SectorTitle,DataTitle,sum(Aug18)[Aug18],sum(Sep18)[Sep18],sum(Oct18)[Oct18],sum(Nov18)[Nov18],sum(Dec18)[Dec18],sum(Jan19)[Jan19],sum(Feb19)[Feb19],sum(Mar19)[Mar19],sum(Apr19)[Apr19],sum(May19)[May19],sum(Jun19)[Jun19],sum(Jul19)[Jul19]
    from tblsomename

    ");
    if($tbl1 === false){
        die( print_r( sqlsrv_errors(), true));
    }
    while( $row = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    echo "<tr>";
    echo "<td rowspan='3'>".$row['SectorTitle']++."</td>";

        while( $row2 = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    $DataTitle=$row2['DataTitle'];
    $Aug=$row2['Aug18'];
    $Sep=$row2['Sep18'];
    $Oct=$row2['Oct18'];
    $Nov=$row2['Nov18'];
    $Dec=$row2['Dec18'];
    $Jan=$row2['Jan19'];
    $Feb=$row2['Feb19'];
    $Mar=$row2['Mar19'];
    $Apr=$row2['Apr19'];
    $May=$row2['May19'];
    $Jun=$row2['Jun19'];
    $Jul=$row2['Jul19'];
    echo "<td>$DataTitle</td><td>$Aug</td><td>$Sep</td><td>$Oct</td><td>$Nov</td><td>$Dec</td><td>$Jan</td><td>$Feb</td><td>$Mar</td><td>$Apr</td><td>$May</td><td>$Jun</td><td>$Jul</td></tr>";
    }

    }

    ?>

The query is not the actual query but gives you an idea as it does pull through the same headers. This is then included into another php file that inserts it between the tags etc.

What my code currently produces is:

enter image description here

Which is correct although i can't seem to get it to loop through the sectortitle bit

Upvotes: 1

Views: 717

Answers (1)

Fabian
Fabian

Reputation: 691

I think you can contend with a single while loop with some added logic to handle the spanned row:

$SectorTitle = "";

while( $row = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    echo "<tr>";

    // Check if there is a new sectortitle
    if($SectorTitle != $row['SectorTitle']) {
        $SectorTitle = $row['SectorTitle'];
        echo "<td rowspan='3'>$SectorTitle</td>";
    }

    $DataTitle=$row['DataTitle'];
    $Aug=$row['Aug18'];
    $Sep=$row['Sep18'];
    $Oct=$row['Oct18'];
    $Nov=$row['Nov18'];
    $Dec=$row['Dec18'];
    $Jan=$row['Jan19'];
    $Feb=$row['Feb19'];
    $Mar=$row['Mar19'];
    $Apr=$row['Apr19'];
    $May=$row['May19'];
    $Jun=$row['Jun19'];
    $Jul=$row['Jul19'];
    echo "<td>$DataTitle</td><td>$Aug</td><td>$Sep</td><td>$Oct</td><td>$Nov</td><td>$Dec</td><td>$Jan</td><td>$Feb</td><td>$Mar</td><td>$Apr</td><td>$May</td><td>$Jun</td><td>$Jul</td></tr>";
}

Upvotes: 2

Related Questions