display data from database into html table

display data from database into html table

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Rendering Database Rows into HTML Tables

When you move from a static HTML page to a dynamic application that fetches data from a database, the logic for rendering that data often breaks. In your specific case, the table isn't showing up because of how PHP handles variables within echo statements and, more critically, how it manages loops versus single-row assignments.

Your current PHP snippet attempts to output headers once but then iterates through results inside a while loop. However, you are echoing the opening <table> tag before the loop starts, and crucially, you are not closing the table tags properly after the loop finishes. Furthermore, there is a logical flaw in your variable handling. You fetch a single row into $row immediately after querying, which overwrites any previous data, but then you immediately enter a while loop that re-fetches rows. This means the first assignment to $row is useless.

The most immediate fix involves restructuring the output logic. You must echo the opening <table> tag once before the loop begins. Then, inside the while loop, you echo each row's data. Finally, and this is often missed, you must echo the closing </table> tag immediately after the loop ends. If your database query returns zero rows, your current code will still print an empty table structure, which can be confusing to users.

Implementing the Fix in Native PHP

Here is how you should restructure the while loop block to ensure the HTML is valid and the data renders correctly:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $type_user = $_POST['type_user'];
    
    // Using prepared statements is highly recommended here to prevent SQL injection
    // even though your current code string-quotes the variable.
    $stmt = $db->prepare("SELECT staff_id, name, email, role FROM user WHERE role = ?");
    $stmt->bind_param("s", $type_user);
    $stmt->execute();
    $run = $stmt->get_result();

    // Always check if there are rows before looping
    if ($run->num_rows > 0) {
        echo "<table>";
        
        // You can define headers once here if you want them inside the loop,
        // or outside. Placing them outside is generally cleaner for performance
        // with large datasets, though negligible for small tables.
        while($row = $run->fetch_assoc()) {
            echo "<tr>";
                echo "<td>" . htmlspecialchars($row['staff_id']) . "</td>";
                echo "<td>" . htmlspecialchars($row['name']) . "</td>";
                echo "<td>" . htmlspecialchars($row['email']) . "</td>";
                echo "<td>" . htmlspecialchars($row['role']) . "</td>";
            echo "</tr>";
        }
        
        echo "</table>"; // Critical: Close the table after the loop
    } else {
        // Handle empty result set gracefully
        echo "<p>No users found for role: " . $type_user . "</p>";
    }
}

Security and Data Escaping

A significant issue in your original code is direct variable interpolation into HTML tags (e.g., echo "<td>".$row['name']."</td>"). If a user's name contains an apostrophe or other special characters, it might break the HTML structure. More dangerously, if your database query logic isn't robust, SQL injection becomes a risk when building SQL strings from user input like $type_user.

Always use prepared statements when interacting with databases to separate code from data. Additionally, always escape output when generating HTML. In native PHP, htmlspecialchars() is the standard function for this. It converts characters like <, >, and & into their HTML entities, ensuring that if a database name is "O'Brien

Our network