So How do I Use This Thing?
To show you the advantages of the HTML_Table class let’s recreate the table we used before, this time using the HTML_Table class.
<?php
//get our query
$connection = mysql_connect("localhost", "me", "password");
$sql = "SELECT * FROM users";
$result = mysql_query($sql, $connection);
//include the class
require_once("/HTML/Table.php");
//set table attributes
$attributes = array("width"=>"100%",
"border"=>"1");
//create the table class
$table = new HTML_Table($attributes);
//build our first row
$contents = array("Name", "E-Mail", "Phone Number");
$attributes = array("bgcolor"="#336699");
$table->addRow($contents, $attributes, "TH");
//loop through and add our data
$attributes = array("bgcolor"="#COCOCO")
while(
$row = mysql_fetch_array($result)) {
$contents = array($row['name'], $row['email'], $row['phone']);
$table->addRow($contents, $attributes);
}
$table->display();
?>
As we can clearly see this approach is much cleaner and more efficient. So lets take a walk through the code and see how it works.
The first part of the code, which retrieves our database results, remains the same. Next we have a require_once statement to include the Table Class into our current document.
Next we define the attributes of our table. This can be done by either creating a string of attributes, or creating an associative array of the attributes and values.
<?php
$attributes = "width="100%" border="1""; //string of attributes
$attributes = array("width"=>"100%", "border"=>"1"); //array of attributes
?>
Now that we have defined the way that we want the table to look we create an instance of the class with our attributes as an argument.
In the next several lines we create the first line of our table. First we define the contents in an array with each element representing a different cell of the table. Next we define the attributes of that row. Then we use the addRow function to add the row to the table. Note that we use the third argument to set the cell type to be a header. The addRow function has the following attributes:
<?php
addRow($contents = null, $attributes = null, $type = 'TD', $inTR = false)
?>
Now that we have a header row, we loop through our database results and add a row to the table for each row of the results.
Lastly we add use the display() function to output our table.