Home > other >  PHP loop to determine first row of a value returned by MySQL
PHP loop to determine first row of a value returned by MySQL

Time:11-22

I have query returned from MySQL data that gets written to a html as a report, it looks very much like this. I would like to set a background color for the first row of each 'Dist' value, in this case rows 1,5,and 9 using CSS. But I am having no luck determining which row that is coming out of MySQL.

NO  CALL    First   St, CO          Dist    Count
1   KD0NBH  John    MO Clay         A       13
2   K0KEX   Rick    MO Platte       A       12
3   N0SAX   Jack    MO Carroll      A       12
4   W0NRP   Neil    MO Jackson      A       12
5   WB0HLW  Charles MO Macon        B       8
6   KD0HHN  Donald  MO Marion       B       4
7   AC0OK   Sam     MO Sullivan     B       2
8   N9MAF   Alan    MO Marion       B       1
9   KF0CTR  Jeffrey MO St. Louis    C       13
10  K0TPY   Paul    MO Franklin     C       12
11  KA0P    David   MO St. Louis    C       10
12  KD0CIV  Dolores MO St. Louis    C       9

$firstdist = ' ';
$liteitup = 'N';
    
    foreach($db_found->query($sql) as $row) {
        if ('$row[district])' <> '$firstdist') 
          {$liteitup = "Y";}
          else {$liteitup = "N";}
 
            $rowno = $rowno   1;  
            
            $netcallsign = '$row[callsign]';
            $Fname    = ucfirst(strtolower('$row[Fname]'));
            $Lname    = '$row[Lname]';
            
            $listing .= "<tr class='$liteitup'>
        <TD>$rowno</td>  <td>$row[callsign]</td>  
        <td>$row[Fname]</td>   <td>$row[Lname]</td> 
        <td>$row[place]</td>  <td>$row[cnt_call]</td>
        </tr>";
        
        $firstdist = "$row[district]";
    }  // End foreach

The class related to $liteitup would then be defined elsewhere. But to do this I need a way to determine which row of each district is the first row. Would some one please help me figure out the loop I need to do this?

CodePudding user response:

Declare a variable before your foreach like $lastDist = null. Then inside the loop do something like

if($lastDist !== $currentDist) {
    // set background color
    $lastDist = $currentDist;
}

That's all there is to it. Whenever the dist changes between iterations that will trigger. null won't match anything so it'll hit on the first iteration too.

  • Related