PHP HTML Table Class

So like most programmers, I do not like to have to replicate code or write the same HTML structures over and over again. This is a PHP Class that allows you to write HTML Tables without writing a single line of HTML. You call the class like this:
<?php
$table_rows = array();
$i = 0;
$results = data_retrieval_function();
foreach ( $results as $result ) {
    $table_rows[$i]['col1'] = $result->title;
    $table_rows[$i]['col2'] = $result->name;
    $table_rows[$i]['col3'] = $result->address;
    $i++;
}
$table = new HTMLTable( array( 'table_class' => 'table table-striped table-bordered' ) );
$table->setHeaders( array( 'Title', 'Name', 'Address' ) );
$table->setTableContent( $table_rows );      
$table->displayTable();      
?>
Now here is what is going on in the code above. You simply loop over your results which become the rows in your table. This builds an array of columns that contain the data for each row. When you instantiate the class you have the following options:
// you pass in an array that gets merged with the defaults with your options overriding the defaults where appropriate
$defaults = array( 
    'table_id' => $table_id,  // this allows you to assign a table id to the table
    'table_class' => 'html_table', // this allows you to assign css classes to the table
    'display_footer' => true // this will turn on and off the <tfoot> with the same column headers as the <thead> <th>s
);     
// there is an auto-incrementing public static variable for table_id that will give the tables unique ids if you do not pass in a value for this.

// the next method that you use is the $class->setHeaders(), which just takes an array of the headers and uses them for the <th>s
Here are some extra features that are completely optional, but are useful when drawing a table. Sometimes you want to assign a class to certain rows. Let's say that you are listing orders and some are in different statuses. For example, some rows might be in the warehouse, some might be shipped and some might be delivered. It would be nice to color code the rows based on the different statuses.
<?php
$table_rows = array();
$i = 0;
$results = data_retrieval_function();
foreach ( $results as $result ) {
    $table_rows[$i]['row_style'] = ( $result->status == 'delivered' ) ? 'delivered' : 'in-warehouse';
    $table_rows[$i]['col1'] = $result->title;
    $table_rows[$i]['col2'] = $result->name;
    $table_rows[$i]['col3'] = $result->address;
    $i++;
}
?>
view/download the class on github
Post a comment
  1. Shahbaz Ahmed Bhatti

    i want learn php classes & function. Can u please also post basic tutorials please






Real Time Web Analytics ^