building a dynamic webpage using php, mysql and smarty [from devscripts.net]

stage one - introduction to this tutorial

Welcome to the devscripts dot net tutorial on how to build a dynamic web page utilising PHP, MySQL and Smarty.
PHP  MySQL  Smarty

This is a step by step guide demonstrating how one would go about building themselves a webpage, or indeed a website using some of the prewritten libraries that are available to the webmaster or web developer.

For this tutorial, you will need access to a web server capable of parsing PHP files, with Smarty installed and a MySQL database running.

If you do not have this set up then you should take a look at the links on stage two of the tutorial.

stage two - tutorial prerequisite reading and useful links

OK I know what PHP and MySQL is, what the hell is Smarty??

Smarty is a template engine for PHP. More specifically, it facilitates a managable way to separate application logic and content from its presentation.

This is best described in a situation where the application programmer and the template designer play different roles, or in most cases are not the same person. For example, let's say you are creating a web page that is displaying a newspaper article. The article headline, tagline, author and body are content elements, they contain no information about how they will be presented.

They are passed into Smarty by the application, then the template designer edits the templates and uses a combination of HTML tags and template tags to format the presentation of these elements (HTML tables, background colors, font sizes, style sheets, etc.)
One day the programmer needs to change the way the article content is retrieved (a change in application logic.) This change does not affect the template designer, the content will still arrive in the template exactly the same. Likewise, if the template designer wants to completely redesign the templates, this requires no changes to the application logic. Therefore, the programmer can make changes to the application logic without the need to restructure templates, and the template designer can make changes to templates without breaking application logic.

Useful links to read before starting coding through this, or to just reference:

Smarty Home Page
Crash Course in using Smarty
Popular Smarty Forums

PHP Home Page
PHP manual

MySQL Home Page
MySQL manual

Linux, Apache, MySQL, PHP setup
Windows, Apache, MySQL, PHP setup

stage three - creating a data source and entering data

In this tutorial we will be writing a news page. In the (MySQL) database will be news articles updated by several different authors using an administration panel (not covered here).

What we are aiming to do is display todays five most recent stories on our page with the minimal amount of database interaction as we run a very busy site.

We will be making use of Smarty's caching functionality to achieve this.

To start with we will need to define the database structure.
We want to store a unique record id, the author who submitted the article, the date and time it was submitted and the article itself.
Using SQL we can create a table like this with the following code:
CREATE TABLE `news` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 255 ) NOT NULL ,
`author` VARCHAR( 255 ) NOT NULL ,
`date` INT NOT NULL ,
`article` LONGTEXT NOT NULL ,
PRIMARY KEY ( `id` ) ,
FULLTEXT (
`article`
)
) TYPE = MYISAM COMMENT = 'This table stores our News Articles';
You can use phpMyAdmin or something similar to fill in a few bogus news articles for testing!

OK so now the data is set up, we need to actually get it back out and displayed on the screen!!

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
$smarty->display('news.tpl');

?>
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!

stage five - creating a template to represent our data

This is basically a HTML page with the addition of some {sections} which are the Smarty sections.

<!-- This is the DOC type declaration and links in the CSS stylesheet etc -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
    <meta name="author" content="Steve Rendell" />
    <meta name="generator" content="EditPlus" />
    <link rel="stylesheet" type="text/css" href="style.css" title="Default CSS Sheet" />

    <title>News Page</title>
  </head>

  <body id="top">

    <!-- OK display the page header to keep it nice-->
    <div id="header">
      <span>Steve's News Page</span>
    </div>

    <!-- This is where the news article will be going -->
    <div id="bodyText">

        <!-- Have a title -->
        <h1 id="welcome">Read All About It</h1>

        <!-- OK this is a section which will loop round for every item in $news (passed in through from PHP) -->
{section name=news loop=$news}
   <!-- For every item, display the Title -->
  <h2 id="{$news[news].id}">{$news[news].title}</h2>
  <!-- Write out the Author information and the date -->
  <h3>{$news[news].author}, {$news[news].date}</h3>
  <!-- Now show the news article -->
  {$news[news].article}
{/section}
    </div>

    <!-- Show copyright information etc -->
    <div id="footer">All Contents Copy Written :)</div>

  <!-- Close the html tags -->
  </body>
</html>
Smarty facilitates a convenient way to loop over arrays of data with the section function. information about the {section} tag

stage six - putting it all together

Now that we have a template, and some PHP to populate it, we should be able to load up the PHP file and get some news articles returned

I used the following CSS stylesheet to get the results below.
h1, h2, h3, #header, #footer {
  font-family: verdana, tahoma, helvetica, arial, sans-serif;
}

h1 {
  font-size: 200%;
  font-weight: bold;
  text-align: center;
}

h2 {
  font-size: 125%;
  font-variant: small-caps;
  color: black;
}

h3 {
  font-size: 85%;
  font-style: italic;
  color: #9B9B96;
}

#header, #footer {
  text-align: center;
  display: block;
  border: 1px solid #999;
  padding: 1mm;
  background: #ffc;
  color: #000;
  color: gray;
  font-variant: small-caps;
}

#header {
  font-size: 250%;
  font-weight: bold;
  margin-bottom: 5mm;
}

#footer {
  font-size: 85%;
  margin-top: 5mm;
}
Here is my smarty powered page in action:

News page showing 2 results

stage seven - conclusions, links and comments

Now in this example it is quite simple to follow, and there isn't really a clear reason behind why you would put in the extra effort to seperate the business and presentation logic, but on larger sites this is a very very useful thing to do.

OK thats the end of the tutorial, any feedback would be appreciated email me as I have never written a tutorial before!

Any mistakes, improvements or just general questions also feel free to get in touch.

Download the source files and CSS here remembering to take note of the password 'devscripts'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值