PHP115
From mi-linux
Jump to navigationJump to searchMain Page >> Web Application Development >> Workbook >> Smarty Template Engine
Please note that this is an advanced topic. Make sure that you have worked through all the previous sections of this workbook before proceeding.
The tutorial on Smarty's official website are rather good, so let's just go through them:
Database example
I have created a simple database + Smarty example on mi-linux, here:
And here is the code for it:
The PHP files
<?php // Set-up Smarty folders and connect to db require("setup_smarty.php"); require("connect_db.php"); // Get data $sql = "SELECT FilmNumber, FilmName, FilmGenre, FilmDuration FROM Films"; $myresult = mysql_query($sql); $total = mysql_num_rows($myresult); // Put data in array while ($row = mysql_fetch_assoc($myresult)) $results[] = $row; // Assign data to template $smarty->assign('total', $total); $smarty->assign('results', $results); // Display template $smarty->display('db.tpl'); ?>
The templates
{include file="header.tpl" title="Smarty rocks!"} <h1>Database example</h1> <p>Displaying {$total} records :</p> <table style="width:200px"> {section name=nr loop=$results} <tr style="background-color:{cycle values="#eeeeee,#dddddd"}"> <td>{$results[nr].FilmName}</td> <td>{$results[nr].FilmGenre}</td> </tr> {sectionelse} <tr><td>No results found!</td></tr> {/section} <table> {include file="footer.tpl"}