Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building html tables from query data... faster?

With my limited experience/knowledge I am using the following structure to generate HTML tables on the fly from MySQL queries:

$c = 0;
$t = count($results);

$table = '<table>';

while ($c < $t) {
   $table .= "<tr><td>$results[0]</td><td>$results[1]</td> (etc etc) </tr>";
   ++$c;
}

$table .= '</table>';

this works, obviously. But for tables with 300+ rows there is a noticeable delay in pageload while the script builds the table. Currently the maximum results list is only about 1,100 rows, and the wait isn't long, but there's clearly a wait.

Are there other methods for outputting an HTML table that are faster than my WHILE loop? (PHP only please...)

like image 894
Drew Avatar asked Apr 07 '10 06:04

Drew


People also ask

Are HTML tables slow?

Sorry to be so vague but generally tables aren't slow to render, but are looked down upon because of their lack of accessibility (although of course much of the idealism is the fact screen readers don't like them).

How do you create a table with 3 columns and 3 rows in HTML?

Creating Tables in HTML You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.

Do Joins slow down query?

Joins: If your query joins two tables in a way that substantially increases the row count of the result set, your query is likely to be slow. There's an example of this in the subqueries lesson. Aggregations: Combining multiple rows to produce a result requires more computation than simply retrieving those rows.


1 Answers

First, probably the slowness is a result of the HTML rendering and not the PHP script. Second, it is not very usable to build very large tables it is better to use paging.

You can improve your script performance in the PHP side in a few ways:

  1. use ob_start(); and ob_get_clean(); - this way the data will be passed to the html at once:

    ob_start();
    // your code here
    echo ob_get_clean();
    
  2. use array and join for strings:

    $str = array();
    $str[] = 'add the strings';
    echo implode($str);
    

BR.

like image 73
aviv Avatar answered Sep 29 '22 22:09

aviv