How can PHP be used to dynamically add classes to table rows fetched from a database using a while loop?

When fetching data from a database and displaying it in a table using a while loop, we can dynamically add classes to table rows based on certain conditions. This can be achieved by using an if statement within the loop to check the data and determine which class to assign to each row. By doing this, we can style the rows differently based on the data being displayed.

<table>
    <?php
    // Fetching data from the database
    while ($row = $result->fetch_assoc()) {
        // Determine the class to be added based on the data
        $class = ($row['status'] == 'active') ? 'active-row' : 'inactive-row';
        
        // Output the table row with the assigned class
        echo "<tr class='$class'>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "</tr>";
    }
    ?>
</table>