devscripts dot net tutorial

building a dynamic webpage using php, mysql and smarty

Development Scripts  Tutorials  Affiliates/Links  Contact Us  About us  Advanced Search

stage four - creating php code to retrieve the data from mysql

If you read the crashcourse for smarty you will see that a PHP page is made up of two distinct parts:
i) The Template - this is how the page should display the data
ii) The PHP - This pulls out the data and sends it to the template.

In this section we will be writing the code on PHP to retrieve the news articles from the database and then to pass that information over into the Smarty Templating Engine to display it to screen.

The PHP code is very simple and is fully commented, so either copy it, or read through it to understand what it going on

// These are the smarty files
require 'libs/Smarty.class.php';

// This is a file which abstracts the DB connecting functionality (Check out PEAR)
require 'DB.php';

$smarty = new Smarty;

$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->use_sub_dirs = false;
$smarty->caching = true;

// This SQL statement will get the 5 most recently added new items from the database
$sql = 'SELECT * ';
$sql .= 'FROM `news` ';
$sql .= 'ORDER BY `id` DESC LIMIT 0, 5';

$result = mysql_query($sql) or die("Query failed : " . mysql_error());

// For each result that we got from the Database
while ($line = mysql_fetch_assoc($result))
 $value[] = $line;

// Assign this array to smarty...
$smarty->assign('news', $value);

// Display the news page through the news template

// Thanks to David C James for a code improvement :)
Notice that we set smarty to use caching
Smarty also has built-in caching capabilities to help speed up the page rendering. A copy of the template output is stored in a text file, then that is displayed upon subsequent calls to the request instead of dynamically rendering the page each time. This can speedup page rendering substantially, especially if there is a lot of processing involved to create the page such as database calls and variable assignments.

This is all the PHP code that we will need to write for this example, so lets move onto the good stuff!
next page