David David - 5 months ago 11
SQL Question

Issue with if statement in PHP code

I first had this code:

foreach( $results as $row ) {
if ($row['class'] <>$class) {
echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
}
echo "
<tr>
<td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td>
</tr>
";
$class = $row['class'];
}
}


That was working fine, but I want that the HTML hyperlink tag disappears when
".$row['hyperlink']."
is equal to
"NULL"
.

For this, I wrote the code like this:

$class = $row['class'];
foreach( $results as $row ) {
if ($row['class'] <>$class) {
echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
}
if ($row['hyperlink'] != "NULL") {
echo "<tr><td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td></tr>";
} else {
echo "<tr><td>".$row['title']."</td></tr>";
}
}
}
?>


Hyperlinks are set or removed as I want, but the grouping function got lost, too.

Instead of:

**Cleaner**
David
Phil
Gustav
**Farmer**
Lynn
Peter
**Mason**
Brion
Alf


I get:

**Cleaner**
David
**Cleaner**
Phil
**Cleaner**
Gustav
**Farmer**
Lynn
**Farmer**
Peter
**Mason**
Brion
**Mason**
Alf


Does anybody know what I did wrong? Where's my fault?

Answer

In your second bit of code, you moved the $class = $row['class']; outside the foreach loop. That means it will initially be set to null (because $row['class'] is undefined before the loop), so $row['class'] <>$class will always be true. Move it back inside the loop and it should work as before.

$class = null; // initialize $class to null
foreach( $results as $row ) {
    if ($row['class'] <>$class) {
        echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
    }
    if ($row['hyperlink'] != "NULL") {
        echo "<tr><td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td></tr>";
    } else {
        echo "<tr><td>".$row['title']."</td></tr>";
    }
    $class = $row['class']; // reset $class to the current value here
}