dbHtmlTable (PHP class)

dbHtmlTable is a PHP class that returns or echoes an html table from a database query result.

See also: more usage examples and the dbHtmlTable download page

PUBLIC METHODS

createTable ..... return or echo the html table (depending on EchoHtml option)
getRowCount ..... return the number of rows (only after calling createTable)
getColumnCount .. return the number of columns (only after calling createTable)
setQuery ........ change the SQL query string
setOption ....... set a single option
setOptions ...... set one or more options
resetOptions .... reset all options to defaults

USAGE

After connecting to your database, a table can be generated as follows:

$HtmlTable = new dbHtmlTable(sqlString, optionsArray);
$HtmlTable->createTable();

or

$HtmlTable = new dbHtmlTable(sqlString);
$HtmlTable->setOptions(optionsArray);
$HtmlTable->createTable();

or

$HtmlTable = new dbHtmlTable(sqlString);
$HtmlTable->setOption(optionName, optionValue);
$HtmlTable->setOption(optionName, optionValue);
$HtmlTable->setOption(optionName, optionValue);
$HtmlTable->createTable();

or some combination thereof. It's also possible (though not necessarily recommended!) to set everything at once and echo the table in one line, by adding a third "force" parameter:

$HtmlTable = new dbHtmlTable(sqlString, optionsArray, true);

The class object can be re-used simply by calling the setQuery() method:

$HtmlTable->setQuery('select MORE from anothertable');
$HtmlTable->createTable();

Calling setQuery() automatically resets some options (those that apply to fields in the previous query, eg field alignment, etc)

See more usage examples

OPTIONS

The following table documents all the options supported by dbHtmlTable.

 General options
Option name Type Description Default Alias
EchoHtml boolean If true, the html is echoed to the browser by createTable(), and nothing is returned. If false, the html is returned as a string and nothing is echoed to the browser. true Echo, EchoIt
TableAttr string Attribute for the HTML table. You might want to set this to something like id="mytable" or class="mytable" to assist with CSS styling. border="1"  
Caption string String to be used as a table caption (HTML <caption> tag). If empty, no caption tag will be used. (empty)  
ShowFieldNames int If 1, field names will be shown at the top of the table. If 2, field names will be shown at the start of each group (see GroupFirst). Otherwise, field names will not be shown at the top. 1 ShowHeader, header
ShowFooter boolean If true, field names will be shown at the bottom of the table. false Footer
HideFields string Normally every field in the query result is shown in the table. HideFields can be a comma-separated list of fields to hide; you might use this if one of the fields is only to be used as part of a LinkField or tooltip. (empty) Hide
NumberFormat string This sets the default format for fields listed in the FormatAsNumber option. The value should be a 4-digit string, with each digit having a special meaning:
  1. currency symbol at start (1=yes, 0=no)
  2. use thousands separator (1=yes, 0=no)
  3. decimal places (0 to 9)
  4. currency symbol at end (1=yes, 0=no)
EXAMPLES:
If this option is 0020 it means no currency symbol at the start, no thousands separator, 2 decimal places and no currency symbol at the end, ie like: 12345.67
Likewise, 1100 means put currency symbol at the start, include thousands separator, no decimal places and no currency symbol at the end, ie like: $12,345

For historical reasons, the NumberFormat can also be a single-digit shortcut

1 means two decimal places, no comma for thousands eg 12345.67 (same as 0020)
2 means dollar sign, two decimal places, with comma for thousands eg $12,345.67 (same as 1120)


The characters used for the currency symbol, thousands separator and decimal can be changed with the Currency, ThousandsSep and DecimalChar options respectively. For example you can format a number as 152,50 € by setting NumberFormat to 0121 with Currency= &euro; ThousandsSep=. and DecimalChar=,.
1  
DateFormat string This sets the default format for fields listed in the FormatAsDate option. It must be a format string as used by the PHP date() function. Example format strings:

j M Y ........ 5 Dec 2010
j M Y H:i .... 5 Dec 2010 15:30
j M Y H:i:s .. 5 Dec 2010 15:30:53
j M Y g:ia ... 5 Dec 2010 3:30pm
j/n/Y ........ 5/12/2010
Y-m-d ........ 2010-12-05
Y-m-d H:i:s .. 2010-12-05 15:30:53
D j F Y ...... Sat 5 December 2010

j M Y  
Currency string Currency symbol used by the NumberFormat and FormatAsNumber options. $ currencysymbol, money
ThousandsSep string Thousands separator character used by the NumberFormat and FormatAsNumber options. , (comma) thousandsep, thou
DecimalChar string Decimal character used by the NumberFormat and FormatAsNumber options. . (dot) decimal
GroupFirst boolean If the first column of your resultset is a repeating value, set this option to true so the value is only shown when it changes. false group, grp
GroupHeadCount integer If GroupFirst is true, this option can specify how many fields should have field names shown (counting from the right). By default, this will be one less than the number of columns, so all field names except the first (repeating) one are shown. This applies to fieldnames both at the top (ShowFieldNames) and bottom (ShowFooter). false  
 Row options
Option name Type Description Default Alias
TrAttr string Attribute for each table row (<tr> tag). This also applies to any totals row, but not header/footer rows. (empty)  
OddRowClass string CSS class name for <tr> tags in odd rows (use this for alternating colours) (empty) oddrow, oddclass
EvenRowClass string CSS class name for <tr> tags in even rows (use this for alternating colours) (empty) evenrow, evenclass
TrEvery string CSS class name to apply to the <tr> tag every N rows. For example brdr@5 will add class="brdr" to every 5th <tr> tag. (empty)  
RowNumber boolean | string If this is true or a non-empty string, an extra column will be added as the first column of the table, for numbering each row. Numbering always start at 1. The value of this option is used as the field name; you can use '&nbsp;' or boolean true if you don't want a field name shown. The cells in this new column will be assigned CSS class "rn", which you can use to style them if required. false rn
GroupResetRow boolean If the resultset is grouped (see GroupFirst), the row counter is reset to 1 for each group (only for the purposes of odd/even classes and TrEvery; the overall RowNumber is not affected by this). To disable this behaviour, set this option to false. true groupreset, grpreset
 Cell options
Option name Type Description Default Alias
TdAttr string Attribute for each table cell (<td> tag). (empty)  
EmptyValue string The value to show for an empty field, eg '(empty)' &nbsp; Empty
NullValue string The value to show for a null field, eg '-null-'. You can also include HTML markup in this string, so for example you could set this to '<span style="color:#888;">-null-</span>' &nbsp; Null
AlignLeft string This is a comma-separated list of fields to left-align. It affects the values and fieldname headings for the specified fields. As with the other Align options, it uses the align attribute of the <td> tag, and will be overruled by any alignment specified in CSS. (empty) left
AlignRight string This is a comma-separated list of fields to right-align. It affects the values and fieldname headings for the specified fields. As with the other Align options, it uses the align attribute of the <td> tag, and will be overruled by any alignment specified in CSS. (empty) right
AlignCentre string This is a comma-separated list of fields to centre-align. It affects the values and fieldname headings for the specified fields. As with the other Align options, it uses the align attribute of the <td> tag, and will be overruled by any alignment specified in CSS. (empty) aligncenter, center, centre
Tooltips?   see the LinkFields option    
FormatAsNumber string A comma-separated list of fields to format as a number. By default, these fields will be formatted according to the NumberFormat option, but you can optionally add a specific format for each field, eg 'BestGuess,Amount=2' (for details, see NumberFormat) (empty) AsNum
FormatAsDate string A comma-separated list of fields to format as a date. By default, these fields will be formatted according to the DateFormat option, but you can optionally add a specific format for each field, eg 'DatePaid,TransDate=j M Y H:i:s' (for details, see DateFormat)
NOTE: format strings specified here CANNOT CONTAIN A COMMA - you would need to encode it so browser shows a comma
(empty) AsDate
CellClass string A comma-separated list of fields with classname/s, eg 'Tmst=myclass,UserId=class2'. In addition to the simple field=class format, you can also apply classes conditionally with the format field=ClassCondValue (or multiple conditions with field=ClassCondValue|ClassCondValue), where
Class is a classname (or space separated class names)
Cond  is a comparison operator. Equals sign is not allowed; use @ instead.
          equal to .......... @
          not equal to ...... ! or !@ or <>
          greater than ...... >
          greater or equal .. >@
          less than ......... <
          less or equal ..... <@
Value is compared with the current value of the field. It can be a static string, or
      a fieldname in square brackets (the value of that field in the current row will be
      substituted). Value can NOT be an expression; if you need something more complex, 
      you could add a calculated field to the SQL as a hidden field and use a comparison 
      with that field.
EXAMPLES: To assign classname "neg" to the Amount field if it's less than zero:
       Amount=neg<0
For same as above, but also assign classname "big" if Amount is more than the Average field:
       Amount=neg<0|big>[Average]
To assign classname "grey" to Tmst if it's empty, and classname "me" to an Id of 6:
       Tmst=grey@,Id=me@6
(empty)  
HeadClass string A comma-separated list of fields with classname/s, eg 'Tmst=myclass,UserId=class2'. This applies a CSS class name to the fieldname headings. (empty)  
ShowTotal string A comma-separated list of fields to be totalled. The totals will appear in a row at the end of the table, with <tr> attribute class="total". (empty) Total
TotalClass string A comma-separated list of fields with classname/s, eg 'Tmst=myclass,UserId=class2'. This applies a CSS class name to the specified field totals. (empty)  
 Link options
Option name Type Description Default Alias
AutoEmailLink boolean If true, any field value that looks like an email address will be rendered as a mailto: link. false  
AutoEmailFields string A comma-separated list of fields that should appear as clickable mailto: links. This is an alternative to AutoEmailLink, which links ALL email addresses it finds. (empty)  
AutoEmailSubject string If not empty, this string will be used as the email subject for mailto: links created for AutoEmailLink or AutoEmailFields options. (empty)  
LinkFields array Allows you to create clickable links and/or tooltips on specific fields. This option, if specified, is an array indexed by FieldName, with each value in the format
    Href~||~Title~||~LinkAttrib
where
    Href ........ location href for the link destination
    Title ....... text to be used as a tooltip (on mouseover)
    LinkAttrib .. any other a attributes, eg 'onclick="doThing();"'

Any of the 3 parts can include the current value of another field in the row by using [FieldName]. For example,
    array('AuthorRef' => 'edit.php?id=[AuthorId]~||~Update this author'
This will create a link on every AuthorRef value, with an href that changes depending on the value of AuthorId in each row. The tooltip for every link will be "Update this author".

If Href is not present, a <span> tag will be created instead of a link (<a> tag). The <span> tag is normally used if you just want a tooltip - any fieldname specified in the Title will usually be included in the HideFields option.

You may need to apply rawurlencode() or htmlentities() to these strings if they include quotes or other special characters.

EXAMPLE: Advanced email link
    $Url = 'mailto:[email]?subject=Subs%20renewal&body=';
    $Url .= rawurlencode("[firstname] [lastname]\r\n\r\nRenew at http://domain.com/renew?qr=[Hash]\r\n");
    // but don't urlencode square brackets!..
    $Url=str_replace(array('%5B', '%5D'), array('[', ']'), $Url);
    $HtmlTable->setOption('LinkFields', array('Hash'=>$Url));
The above example will create a mailto: link on the Hash field, where the email To address will be the value from the email field, and the email body will begin with values from the firstname and lastname fields.
(empty) Link

More usage examples | dbHtmlTable download page