Create table with PHP and populate from MySQL

Create table with PHP and populate from MySQL

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

Stefan Bogdanescu

Founder & Senior Architect

Dynamic Tables: Populating HTML from PHP and JavaScript

Building a dynamic table where data flows directly from a MySQL database into an HTML view is a fundamental task in web development. However, mixing server-side rendering with client-side logic often leads to confusion about where the HTML actually gets generated. In your specific case, you are attempting to load a PHP file via a <script> tag to render a table. While this approach shows signs of execution (as seen in FireBug), it fundamentally misunderstands how the browser and server interact.

The core issue is that a <script src="..."> tag only loads JavaScript code; it does not execute PHP scripts. When the browser encounters <script src="/Management/Employee_Management.php">, it treats the response as raw text, not executable code. If your PHP file contains an echo statement expecting to output HTML directly into the DOM, the browser will simply display the raw text or fail to parse the tags if they are nested within a script block intended for JS.

To make this work, you must ensure that the PHP file outputs valid HTML strings that can be safely inserted into your page. Since you want to separate the logic into a distinct file, you have two viable architectural paths: server-side rendering or client-side injection.

Server-Side Rendering (The Standard Approach)

The most robust method is to let the browser handle the full request-response cycle for the HTML document itself. Instead of trying to "inject" PHP code into an existing page via JavaScript, the initial HTML file should request a partial view from the server.

You can modify your entry point to fetch the table data and render it on the server before sending the response to the browser. This is often cleaner than trying to parse raw strings in JavaScript.

In your main Employee_Management.php (or an index file), you would include the logic to generate the table directly:

<?php
// Database connection details should be secure and out of reach
$host = 'localhost';
$db   = 'your_database';
$user = 'db_user';
$pass = 'db_password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
    
    $stmt = $pdo->query("SELECT id, l_name, f_name, ssn FROM employees");
    $employees = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Employee Management</title>
    <style>
        table { width: 100%; border-collapse: collapse; }
        td, th { border: 1px solid #ddd; padding: 8px; }
        .table_odd_row { background-color: #f2f2f2; }
        .table_even_row { background-color: #ffffff; }
    </style>
</head>
<body>
    <h2>Employee List</h2>
    
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Last Name</th>
                <th>First Name</th>
                <th>SSN</th>
            </tr>
        </thead>
        <tbody>
<?php foreach ($employees as $row): ?>
            <tr class="<?php echo ($loopIndex = count($employees) - array_search($row, $employees)) % 2 == 0 ? 'table_odd_row' : 'table_even_row'; ?>">
                <td><?php echo htmlspecialchars($row['id']); ?></td>
                <td><?php echo htmlspecialchars($row['l_name']); ?></td>
                <td><?php echo htmlspecialchars($row['f_name']); ?></td>
                <td><?php echo htmlspecialchars($row['ssn']); ?></td>
            </tr>
<?php endforeach; ?>
        </tbody>
    </table>

</body>
</html>
<?php
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>

This approach eliminates the need for complex JavaScript loading mechanisms. The server sends a complete HTML document containing the generated table, ensuring that styles and scripts are parsed correctly by the browser. It also handles the alternating row colors naturally within the loop, though note that calculating the class based on global index can be tricky if rows are filtered; using a counter or an array_filter logic is often safer than relying on raw iteration counts without context.

Client-Side Injection via AJAX

If you strictly require the HTML to exist in a separate .html file and load the data dynamically, you must use AJAX (fetch) rather than a <script src> tag. The server endpoint should return only the HTML fragment of the table body or the full table markup as a string.

document.addEventListener('DOMContentLoaded', function() {
    fetch('/Management/Employee_Management.php?action=Edit_Employee')
        .then(response => response.text()) // Request text/html, not JSON
        .then(data => {
            // Inject the data into the DOM
            document.getElementById('table-container').innerHTML = data;
        })
        .catch(error => console.error('Error loading table:', error));
});

In this scenario, your PHP endpoint must output only the HTML string (the table tags), not wrap it in PHP logic that expects a full page context. You can use the htmlspecialchars function to escape variables like $wrap_id, $wrap_l_name, etc., to prevent XSS vulnerabilities when rendering user data like SSNs or names.

Addressing Legacy Code Risks

Your original snippet used mysql_query, which is deprecated and removed in newer versions of PHP (8.1+). If you are upgrading your stack, you must migrate to PDO or MySQLi. The legacy extension poses significant security risks, particularly SQL injection, if not handled with prepared statements. Your current code concatenates variables directly into the query string without sanitization.

Furthermore, the logic for alternating row colors in your loop relies on $i % 2. If your database query returns an empty set or if the loop is interrupted by an error, this logic breaks. Always check if $result has data before iterating.

By shifting to PDO and ensuring your HTML structure is generated either entirely on the server or via a controlled AJAX fetch, you resolve the issue of the table not displaying. The key takeaway is that <script src> loads scripts; it does not render PHP views. To get dynamic HTML from a separate file, the browser must treat the response as text content to be injected into the document flow.

Our network