Using database in PEAR and Smarty
For using database, you need to install a package of PEAR called ‘MDB2’ along with the installation of PEAR and Smarty.
MDB2 provides a common API for all support RDBMS.
Connecting to database
To connect to a database through PEAR::MDB2, you have to create a valid DSN – data source name. This DSN consists in the following parts:
phptype: Database backend used in PHP (i.e. mysql , pgsql etc.)
dbsyntax: Database used with regards to SQL syntax etc.
protocol: Communication protocol to use ( i.e. tcp, unix etc.)
Sample Application use Smarty: Guestbook – Part 5
We have two templates for our guestbook, one for viewing and one for adding a new entry.
/web/www.example.com/smarty/guestbook/templates/guestbook.tpl
{* Smarty *}
<table border="0" width="300">
<tr>
<th colspan="2"; bgcolor="#d1d1d1">Guestbook Entries (<a href="{$SCRIPT_NAME}?action=add">add</a>)</th>
</tr>
{foreach from=$data item="entry"}
<tr> bgcolor="{cycle values="#dedede,#eeeeee" advance=false}">
<td> {$entry.Name|escape}</td>
<td align="right">{$entry.EntryDate|date_format:"%e %b, %Y %H:%M:%S"}</td>
</tr>
<tr>;
<td colspan="2" bgcolor="{cycle values="#dedede,#eeeeee"}">{$entry.Comment|escape}</td>
</tr>
{foreachelse}
<tr>
<td colspan="2">No records</td>
</tr>
{/foreach}
</table>
Sample Application use Smarty: Guestbook – Part 4
/web/www.example.com/smarty/guestbook/libs/guestbook.lib.php
< ?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: guestbook.lib.php
* Version: 1.0
*/
/**
* guestbook application library
*
*/
class Guestbook {
// database object
var $sql = null;
// smarty template object
var $tpl = null;
// error messages
var $error = null;
/**
* class constructor
*/
function Guestbook() {
// instantiate the sql object
$this->sql =&amp; new GuestBook_SQL;
// instantiate the template object
$this->tpl =&amp; new Guestbook_Smarty;
}
/**
* display the guestbook entry form
*
* @param array $formvars the form variables
*/
function displayForm($formvars = array()) {
// assign the form vars
$this->tpl->assign('post',$formvars);
// assign error message
$this->tpl->assign('error', $this->error);
$this->tpl->display('guestbook_form.tpl');
}
/**
* fix up form data if necessary
*
* @param array $formvars the form variables
*/
function mungeFormData(&amp;$formvars) {
// trim off excess whitespace
$formvars['Name'] = trim($formvars['Name']);
$formvars['Comment'] = trim($formvars['Comment']);
}
/**
* test if form information is valid
*
* @param array $formvars the form variables
*/
function isValidForm($formvars) {
// reset error message
$this->error = null;
// test if "Name" is empty
if(strlen($formvars['Name']) == 0) {
$this->error = 'name_empty';
return false;
}
// test if "Comment" is empty
if(strlen($formvars['Comment']) == 0) {
$this->error = 'comment_empty';
return false;
}
// form passed validation
return true;
}
/**
* add a new guestbook entry
*
* @param array $formvars the form variables
*/
function addEntry($formvars) {
$_query = sprintf(
"insert into GUESTBOOK values(0,'%s',NOW(),'%s')",
mysql_escape_string($formvars['Name']),
mysql_escape_string($formvars['Comment'])
);
return $this->sql->query($_query);
}
/**
* get the guestbook entries
*/
function getEntries() {
$this->sql->query(
"select * from GUESTBOOK order by EntryDate DESC",
SQL_ALL,
SQL_ASSOC
);
return $this->sql->record;
}
/**
* display the guestbook
*
* @param array $data the guestbook data
*/
function displayBook($data = array()) {
$this->tpl->assign('data', $data);
$this->tpl->display('guestbook.tpl');
}
}
?>
Sample Application use Smarty: Guestbook – Part 3
/web/www.example.com/smarty/guestbook/libs/sql.lib.php
< ?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: sql.lib.php
* Version: 1.0
*/
// define the query types
define('SQL_NONE', 1);
define('SQL_ALL', 2);
define('SQL_INIT', 3);
// define the query formats
define('SQL_ASSOC', 1);
define('SQL_INDEX', 2);
class SQL {
var $db = null;
var $result = null;
var $error = null;
var $record = null;
/**
* class constructor
*/
function SQL() { }
/**
* connect to the database
*
* @param string $dsn the data source name
*/
function connect($dsn) {
$this->db = DB::connect($dsn);
if(DB::isError($this->db)) {
$this->error = $this->db->getMessage();
return false;
}
return true;
}
/**
* disconnect from the database
*/
function disconnect() {
$this->db->disconnect();
}
/**
* query the database
*
* @param string $query the SQL query
* @param string $type the type of query
* @param string $format the query format
*/
function query($query, $type = SQL_NONE, $format = SQL_INDEX) {
$this->record = array();
$_data = array();
// determine fetch mode (index or associative)
$_fetchmode = ($format == SQL_ASSOC) ? DB_FETCHMODE_ASSOC : null;
$this->result = $this->db->query($query);
if (DB::isError($this->result)) {
$this->error = $this->result->getMessage();
return false;
}
switch ($type) {
case SQL_ALL:
// get all the records
while($_row = $this->result->fetchRow($_fetchmode)) {
$_data[] = $_row;
}
$this->result->free();
$this->record = $_data;
break;
case SQL_INIT:
// get the first record
$this->record = $this->result->fetchRow($_fetchmode);
break;
case SQL_NONE:
default:
// records will be looped over with next()
break;
}
return true;
}
/**
* connect to the database
*
* @param string $format the query format
*/
function next($format = SQL_INDEX) {
// fetch mode (index or associative)
$_fetchmode = ($format == SQL_ASSOC) ? DB_FETCHMODE_ASSOC : null;
if ($this->record = $this->result->fetchRow($_fetchmode)) {
return true;
} else {
$this->result->free();
return false;
}
}
}
?>
Sample Application use Smarty: Guestbook – Part 2
We’ll start with index.php, the entry point of our application. This is the file directly accessed by the web browser.
/web/www.example.com/docs/guestbook/index.php
?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: index.php
* Version: 1.0
*/
// define our application directory
define ('GUESTBOOK_DIR', '/web/www.example.com/smarty/guestbook/' );
// define smarty lib directory
define ('SMARTY_DIR', '/usr/local/lib/php/Smarty/' );
// include the setup script
include( GUESTBOOK_DIR . 'libs/guestbook_setup.php' );
// create guestbook object
$guestbook=& new Guestbook< // set the current action
$_action= isset ($_REQUEST['action']) ? $_REQUEST ['action'] : 'view';
switch($_action) {
case 'add' :
// adding a guestbook entry
$guestbook->displayForm();
break;
case 'submit':
// submitting a guestbook entry
$guestbook->mungeFormData ($_POST);
if($guestbook->isValidForm($_POST)) {
$guestbook->addEntry($_POST);
$guestbook->displayBook($guestbook->getEntries());
} else {
$guestbook->displayForm($_POST);
}
break;
case 'view':
default:
// viewing the guestbook
$guestbook->displayBook($guestbook->getEntries());
break;
}
?>
Is Smarty right for me?
Although Smarty is known as a “Template Engine”, it would be more accurately described as a “Template/Presentation Framework.” That is, it provides the programmer and template designer with a wealth of tools to automate tasks commonly dealt with at the presentation layer of an application. I stress the word Framework because Smarty is not a simple tag-replacing template engine. Although it can be used for such a simple purpose, its focus is on quick and painless development and deployment of your application, while maintaining high-performance, scalability, security and future growth.
Here are some of the more notable features of Smarty:
Caching: Smarty provides fine-grained caching features for caching all or parts of a rendered web page, or leaving parts uncached. Programmers can register template functions as cacheable or non-cachable, group cached pages into logical units for easier management, etc.
Continue reading »


