What is the best way to implement a counter function in PHP when displaying data from a database in a table?

When displaying data from a database in a table, you can implement a counter function in PHP to number each row in the table. This can be achieved by initializing a variable outside the loop that fetches the data from the database, incrementing it within the loop, and displaying it in the table. This way, each row will have a unique number assigned to it.

<?php
// Connect to your database

// Query to fetch data from the database
$query = "SELECT * FROM your_table";
$result = mysqli_query($connection, $query);

// Initialize a counter variable
$counter = 1;

// Display data in a table with row numbers
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $counter . "</td>";
    echo "<td>" . $row['column1'] . "</td>";
    echo "<td>" . $row['column2'] . "</td>";
    // Add more columns as needed
    echo "</tr>";
    
    // Increment the counter
    $counter++;
}
echo "</table>";

// Close the database connection
mysqli_close($connection);
?>