Search code examples
phpmysqlsqllegacy

Query formatting help (PHP, MySQL) Legacy code


This code is used to show a list of stuff...

$result= mysql_query("
SELECT DISTINCT 
m.username, m.asdf_txt, m.week_txt,  
   FROM table m  
      WHERE m.username='$user' ORDER BY m.week_txt ASC") 
or die(mysql_error($link));

while($row = mysql_fetch_array($result)) { 
    echo "<br>" . $row['week_txt'] . ""; 
    echo "<br>" . $row['asdf_txt'] . ""; 
} 
echo "<br>"; echo "";

It ends up showing

Week 1
asdfasdf1

Week 1
asdfasdf2

Week 2
asdfasdf3

Week 2
asdfasdf4

But I would like to have instead...

Week 1
asdfasdf1

asdfasdf2

Week 2
asdfasdf3

asdfasdf4

Any suggestions would be helpful. I'm looking for a solution that will be written into the code (a php/mysql file) itself. Bear in mind I've solved this problem with the following code in a more roundabout way previously...

sed 's/<br>Week 1\b//2g; s/<br>Week 2//2g;'

Solution

  • Try This

    $prev = "";
    while($row = mysql_fetch_array($result)) {
        if (strcmp($row['week_text'],$prev)){
           echo "<br>" . $row['asdf_txt'] . "";
        } else {
           echo "<br>" . $row['week_txt'] . ""; 
           echo "<br>" . $row['asdf_txt'] . "";
        }
        $prev = $row['week_text']; 
    }