tags:

views:

13

answers:

1

The following code brings up all the fixtures from the database.

    while ($row = mysql_fetch_assoc($result)) 
    {
        echo $row['date'];
        echo $row['home_user'];
        echo $row['home_team'];
        echo $row['away_user'];
        echo $row['away_team'];
    }

The problem I have is all the fixtures are just listed. There are many fixtures with the same dates. For each date(timestamp), there are 10 fixtures. What I am trying to achieve is each date printed and then the fixtures for that date underneath. Is this possible? Thanks

A: 

This is a common question for users of SQL databases. It's natural to report information in this kind of way, however relational query results are always "square" -- that is, every row has the same columns, and every column must exist on every row. So the shape of a query result doesn't fit how you want to display it.

The easiest way to do what you want is to include the date on every row of the query result, and then echo it conditionally, only when it changes:

$prevDate = '';
while ($row = mysql_fetch_assoc($result)) 
    {
        if ($row['date'] != $prevDate) {
            echo 'DATE: ' . $row['date'];
            $prevDate = $row['date'];
        }
        echo $row['home_user'];
        echo $row['home_team'];
        echo $row['away_user'];
        echo $row['away_team'];
    }

Be sure to write your SQL query to ORDER BY date.

Bill Karwin
Is there anyway I can actually format these into blocks of fixtures? At the moment there is just one long continuous list of fixtures. I can't really think of a way to do this?
Luke
That's an output formatting question. I'd suggest using nested `<ul>` tags if you're talking about HTML output.
Bill Karwin
Could I possibly use a foreach statement for each date and then loop through a second query just for fixture within that date?
Luke
You could, but this leads to executing N+1 queries: one query to get a list of distinct dates, and an additional query for the group of fixtures for each respective date. Running N+1 queries is a lot less efficient than running 1 query, and using a simple `if()` block as I showed above.
Bill Karwin