PHP echo tables

PHP echo tables

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

Stefan Bogdanescu

Founder & Senior Architect

Refactoring PHP Echo Tables for Readability and Security

Displaying database results directly from a while loop often leads to what developers call "echo tables." These are grids where every row is hard-coded into the output string, making the logic difficult to read and the application vulnerable to security flaws. The source scenario describes a common pattern: retrieving product data from MySQL and attempting to render it with inline HTML tags like <br> for spacing and hardcoded image dimensions.

While this approach works functionally, it fails on maintainability and safety. The primary issue is the lack of separation between logic and presentation. When you manually echo every <tr>, <td>, and closing tag inside a loop, you are repeating HTML structure for every single record. This creates code that is verbose, hard to debug, and impossible to style flexibly without injecting massive blocks of CSS.

The Security Gap in Legacy Code

The most critical technical debt in the provided example is the use of the mysql_* functions. These deprecated extensions were removed from core PHP 7.0 due to severe security vulnerabilities. They do not support prepared statements, making them highly susceptible to SQL injection attacks. If an attacker can manipulate input, they can execute arbitrary commands on the database server.

Modern development requires switching to PDO or MySQLi with prepared statements. This ensures that user data is never concatenated directly into the query string. For instance, instead of:

$sql = mysql_query("SELECT * FROM products");

You should use a PDO connection where you can safely handle parameters. Even if the dataset is static and no user input filters the query, adhering to prepared statements is a non-negotiable security baseline for any application accessing a database.

Structural Refactoring with Template Logic

To achieve the "messy to clean" transformation shown in the source material's second image, you must stop echoing HTML tags inside the loop. Instead, construct the data array first and render it later using a template or a helper function. This technique is known as the separation of concerns.

You can refactor the PHP logic to return an associative array from the query:

$products = [];
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    // Normalize keys to match your desired HTML structure
    $products[] = [
        'name' => $row['product_name'],
        'image' => htmlspecialchars($row['product_image']),
        'quantity' => $row['product_qua'],
        'price' => $row['product_price'],
        'description' => htmlspecialchars($row['product_des'])
    ];
}

Notice the use of htmlspecialchars(). This is essential when echoing user-generated content or data from a database into HTML attributes. If an image URL contains a malicious script or if the description contains <script> tags, this function sanitizes the output to prevent Cross-Site Scripting (XSS) attacks.

Implementing the Layout

Once the data is prepared in a clean array, you can define the HTML structure outside the loop. This allows you to handle empty states gracefully—such as displaying a "No products found" message if $products is empty—and keeps your code DRY (Don't Repeat Yourself).

The resulting HTML table will have distinct columns for Name, Image, Quantity, Price, and Description. You can now apply CSS classes to these columns individually. For example, the image column might require a specific aspect ratio container to prevent layout shifts when different products have varying image dimensions, rather than relying on fixed width='200px' attributes which break responsive designs.

If you are working within the Laravel ecosystem, this pattern maps directly to Blade templates. You would pass the $products array from your controller and iterate over it using @foreach, utilizing Blade's sectioning directives to keep the layout modular. For more complex applications or those built on top of Laravel, leveraging the official documentation at LaravelCompany can provide deeper insights into optimizing database interactions and view rendering.

Styling for Responsiveness

The original CSS used float:left and a fixed border. While functional, this is an outdated technique that prevents responsive stacking on mobile devices. Modern tables should use standard block-level layouts or CSS Grid/Flexbox to ensure the product cards stack vertically on smaller screens.

By moving away from inline styles like height='200px', you allow the container to adapt to the content. You can instead set a maximum height and add overflow scrolling properties, ensuring that large image files do not break the page layout while maintaining visual consistency across different browsers.

Our network