Difference between revisions of "PHP115"

From mi-linux
Jump to navigationJump to search
Line 52: Line 52:
 
<pre>
 
<pre>
 
<?php
 
<?php
 +
  // setup_smarty.php
 +
 
   // Include Smarty.class.php
 
   // Include Smarty.class.php
 
   require('libs/Smarty.class.php');
 
   require('libs/Smarty.class.php');
Line 68: Line 70:
 
<pre>
 
<pre>
 
<?php
 
<?php
 +
  //connect_db.php
 +
 
   // Connect to db
 
   // Connect to db
 
   $dbServer=mysql_connect("localhost","xxxx","xxxx");
 
   $dbServer=mysql_connect("localhost","xxxx","xxxx");

Revision as of 12:19, 7 November 2012

Main 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

The main file:

<?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');
    
?>

As you can see it includes a couple of files:

  • setup_smarty.php: Smarty set-up
  • connect_db.php: connection to your database
<?php
  // setup_smarty.php

  // Include Smarty.class.php
  require('libs/Smarty.class.php');

  // Create Smarty object
  $smarty = new Smarty();

  // Set-up Smarty folders
  $smarty->template_dir = 'templates';
  $smarty->compile_dir = 'templates_c';
  $smarty->cache_dir = 'cache';
  $smarty->config_dir = 'configs';
?>
<?php
  //connect_db.php

  // Connect to db
  $dbServer=mysql_connect("localhost","xxxx","xxxx");
  if (!$dbServer) {echo "Failed to connect to MySQL"; exit; }
  mysql_select_db("xxxx",$dbServer);
?>

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"}