Group TD (table data) without using rowspan when left joining in mySQL

When outputting data from a database using left joins you often get redundant data in your output.  Say you have a table with vendor information, and a second table containing the customers for each vendor.  If you want to display a table with the vendor names and their customers, you’ll most likely want to use a left join.

The problem is, when you output your data you’ll repeat the vendor name for each customer they have.  It makes the table look cluttered and hard to read.  Not to worry though, there is an easy solution!

All you have to do is create 2 classes:

.noblanktd{color:inherit; border-top:1px solid #000; border-top:1px solid #000}
.blanktd{color:white; }

and here’s the php code:

function outputmystuff(){
// get your data here eg
$query = “SELECT v.id, v.name as vendorname, c.name as customername FROM vendors as v LEFT JOIN customers as c ON v.id = c.vendor_id”;
$result = mysql_query($query);

$oldID = false;
while($row = mysql_fetch_assoc($result)){
$ID = $row[‘id’];
if($oldID == $ID){
$class = ‘blanktd’;
} else{
$class = “noblanktd”;
}
$returnval .= <<<EOD
<tr>
<td class=”{$class}”>{$row[‘vendorname’]}</td>
<td class=”noblanktd”>{$row[‘customername’]}</td>
</tr>
EOD;
$oldID = $ID;

}

return $returnval;

}

and last but not least the html

<table class=”repTable”>
<tr>
<th>Vendor Name</th>
<th>Customer Name</th>
</tr>
<?=outputmystuff()?>
</table>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top