Sunday, April 16, 2006

Generic Smarty Template to make Report from SQL Query

Smarty is an awesome template engine for php developers. It gives you ultimate flexibility over your template. Short learning curve, easy syntax and performance makes it really unbetable. Yesterday night I designed a generic smarty template which can take an array of records and display them in a table.

source of autoreport.tpl

<table class="auto_table">
{if $headers ne ""}
<tr class="auto_header_row">
{section name=header_offset loop=$headers}
<th class="auto_header">{$headers[header_offset]}</th>
{/section}
</tr>
{/if}
{foreach item=row from=$data}
<tr class="auto_data_row">
{section name=column_offset loop=$row}
<td class="auto_data">
{$row[column_offset]}
</td>
{/section}
</tr>
{/foreach}
</table>

So how to use that template? take a look at this code

<?
// connect to your db, say mysql
$records = array();
$result = mysql_query("select name, roll from tablename");
while ($row = mysql_fetch_row($result))
{
$records[] = $row;
}

$smarty->assign("data",$records);
$smarty->assign("headers",array("name","roll"));
$smarty->display("autoreport.tpl");
?>

Thats it!!

0 Comments:

Post a Comment

<< Home