How can a PHP beginner effectively implement a counter in a table generated from a MySQL query result?

To implement a counter in a table generated from a MySQL query result, you can create a variable outside the loop that increments with each iteration. Inside the loop, you can then display this counter value for each row in the table.

<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Perform a query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Initialize counter
$counter = 1;

// Display results in a table
echo "<table>";
while($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $counter . "</td>";
    echo "<td>" . $row['column1'] . "</td>";
    echo "<td>" . $row['column2'] . "</td>";
    echo "</tr>";
    $counter++;
}
echo "</table>";

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