Smarty instance tutorial (using PHP built-in MYSQL functions)

Source: Internet
Author: User
Tags constant constant definition mysql functions php code table name create database

Starting from this section, we will learn how to apply Smarty to the actual example. for demonstration purposes, I will use a previously written website as an instance. first, let me explain that my art skills are not very strong, so the pages I designed are not very nice. Let's take a look at them.
Before reading this document, you can first look at indexbak.htmand newsbak.htm, which are the example diagrams we have generated.

I. First, let's explain the database we are going to use. Below I will first give you the database source file for example:


Create database News;

USE News;

/****************************
*
* Table name: tb_news_ch
* Usage: domestic news table
*
****************************/
Create table tb_news_ch
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);


/****************************
*
* Table name: tb_news_in
* Usage: international news table
*
****************************/
Create table tb_news_in
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);


/****************************
*
* Table name: tb_news_mu
* Usage: Entertainment News table
*
****************************/

Create table tb_news_mu
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);
Here I will briefly describe the database.

First question:
We can see that the field names of the three data tables are the same, so why not combine them into a data table? The answer is simple: efficiency, during development, we may not feel any improvement in efficiency. However, when the website runs for a period of time, its news data volume will become very large, in addition, if the website becomes larger in the future, all types may be separated to form a website similar to china.xxx.com, international.xxx.com, and music.xxx.com, and each column will be separately divided into physical sites, at that time, if news is still put together, it will lead to database bottlenecks. Therefore, it is reasonable to separate the current sites.

Second question:
Someone may ask, what is the I, vc, and lt used before the field? The name is based on the field type, which is also a good style. You can know the type of a field by placing the type prefix before the variable, this is a reference from Microsoft's Hungary naming method. During database design, I first defined each type as 1-3 letters, then add the corresponding code before each field to represent its type. as shown in the preceding figure, the field types of each database are defined:

Integer I
Varchar vc
Longtext lt
Char c
....

During use, you can enter 5 data records in each data table for use during instance debugging.

II. Sample site directory structure:

PHP code :--------------------------------------------------------------------------------
+ Web (site root directory)
|
| ---- + Comm (Smarty Documentation Directory)
|
| ---- + Plugins (Smarty plug-in directory)
| ----- Config_File.class.php (Smarty configuration file)
| ----- Smarty. class. php (master Smarty file)
| ----- Smarty_Compiler.class.php (Smarty compilation class file)
|
| ---- + Cache (Smarty cache directory, which guarantees read and write permissions under * nix)
|
| ---- + Templates (website template file storage directory)
|
| ---- Header. tpl (page header template file)
| ---- Index. tpl (website homepage template file)
| ---- Foot. tpl (page footer template file)
| ---- News. tpl (news page template file)
|
|
| ---- + Templates_c (directory for storing template files after compilation, and read/write permission for * nix)
|
| ---- + Css (site CSS file directory)
|
| ---- + Image (site image directory)
|
| ---- + Media (website Flash animation storage directory)
|
| ----Indexbak.htm (original homepage effect chart)
|
| ---- Newsbk, htm (original news page effect)
|
| ---- Index. php (Smarty homepage program file)
|
| ---- News. php (Smarty news display file)
|
| ------Example .txt (Directory Description)
|
| ------Data warehouse creation file .txt (database creation document)

For details, download the instance and compare the structure.

--------------------------------------------------------------------------------

III. Instance fragments in the template:

1. index. tpl:

Index. tpl is the template class of the site homepage. After opening its source file, we can see the following two sentences:
========================================================== ============
1. <{* The following sentence is the page header of this page *}>
2. <{include file = "header. tpl"}>
========================================================== ============
The first sentence is a template comment.
The first sentence indicates that another file is to be included in the current position. What file? header. tpl, the header here. tpl is the standard page header file of the page. It is used to separate this part so that it can be reused on other pages. Traditionally, you should write the page header file in a table, however, some of my instances are not compliant with the specifications.

Let's look at the last sentence:
========================================================== ==========
3. <{include file = "foot. tpl"}>
========================================================== ==========
Needless to say, everyone understands that it contains a footer file.

Let's take a look at the template code of the domestic news section:


CODE: [Copy to clipboard] <table width = "100%" border = "0" cellpadding = "0" cellspacing = "0" bgcolor = "# B9E9FF">
<Tr>
<Td height = "115" width = "10"> </td>
<Td valign = "top" width = "295" bgcolor = "# B9E9FF">
<{Section name = loop = $ News_CH}>
<Li class = "newsfont"> <a href = "news. php? Type = 1 & id = <{$ News_CH [loop]. NewsID}> "class =" newsfont "> <{$ News_CH [loop]. NewsTitle}> </a>
<{/Section}>
</Td>
</Tr>
</Table>
For more information, see <{section}> and <{/section}>. The other parts are listed to better understand the meaning of the code. Can you see it? Here, I will review the previous content: I have defined a section loop template block named loop, which loops through the $ News_CH array, a link is generated for the current news at <a href = "xxxx"> and the address is news. php? Type = 1 & id = xxx. Here, xxx is the extracted iNewsID from the database. It refers to the news with id to be displayed on the news display page. $ News_CH [loop]. Does NewsTitle understand this representation? If you don't understand it, take a look at the <{section}> syntax in the "Smarty instance teaching-program design" section described in the previous section.
You may feel a little unfamiliar with <{}>. Here, <{}> defines blocks for template statements. We use {} in the first two sections, but this is a specific application, so we will not take {}, which is expressed by <{}> that everyone is used to. Of course, this is in. in the php file.

Let's look at the code for international news and entertainment news:


International news:


CODE: [Copy to clipboard] <table width = "100%" border = "0" cellpadding = "0" cellspacing = "0">
<Tr>
<Td width = "295" height = "115" valign = "top">
<{Section name = loop = $ News_IN}>
<Li class = "newsfont"> <a href = "news. php? Type = 2 & id = <{$ News_IN [loop]. NewsID}> "class =" newsfont "> <{$ News_IN [loop]. NewsTitle}> </a>
<{/Section}>
</Td>
</Tr>
</Table>
Entertainment news:


CODE: [Copy to clipboard] <table width = "100%" border = "0" cellpadding = "0" cellspacing = "0">
<Tr>
<Td width = "296" height = "115" valign = "top">
<{Section name = loop = $ News_MU}>
<Li class = "newsfont"> <a href = "news. php? Type = 3 & id = <{$ News_MU [loop]. NewsID}> "class =" newsfont "> <{$ News_MU [loop]. NewsTitle}> </a>
<{/Section}>
</Td>
</Tr>
</Table>
Are there any differences? The loop part is different. The loop refers to the array to be cyclic. Note that the loop of multiple sections cannot be specified as the same value, in this case, the Smarty analysis template analyzes two sections with the same name at the same time and generates two identical records.

When you see this, someone will have a question: I already have a loop block. How can I display it in the current position only the number of records we want? This problem is simple. We control the number of cycles of the section loop block of Smarty in the. Php file to replace the array of the loop block. We don't need to consider it when designing the template.


Next, let's take a look at news. tpl:

1. Read this sentence:
<Title> <{$ NewsTitle}> ---- Tianyao information network </title>
The title of the news page to be displayed is the news title + "---- Tianyao Information Network"
2. News Title:
<Div align = "center" class = "NewsTitle"> <{$ NewsTitle}> </div>
Here, a template variable $ NewsTitle is set to replace $ NewsTitle (including the title bar) with the title of the current news in the database.
3. News content:
<P> <{$ NewsContext}> </p>
This sentence is also easy to show news content in the current position.

Of course, here we will simply list the news. In actual applications, you can also list the source, posting time, author, and related news of the article, I will not discuss it much here.


III. Procedure:

1. Let's take a look at the index. php source file, and then let's analyze its role slowly:

Index. php


<? Php

2. include_once ("./comm/Smarty. class. php"); // contains the smarty class file
3. define ("NUM", 5); // defines the number of news entries displayed each time.

4. $ smarty = new Smarty (); // Create a smarty instance object $ smarty
$ Smarty-> templates_dir = "./templates"; // set the template directory
$ Smarty-> compile_dir = "./templates_c"; // Set the compilation Directory
$ Smarty-> cache_dir = "./cache"; // you can specify a cache directory.
$ Smarty-> cache_lifetime = 60*60*24; // you can specify the cache time.
$ Smarty-> caching = false; // set this parameter to false during debugging. Use true for release.
$ Smarty-> left_delimiter = "<{"; // you can specify the left boundary.
$ Smarty-> right_delimiter = "}>"; // you can specify the right boundary.


5. $ db = mysql_connect ("localhost", "root ","");
Mysql_select_db ("News", $ db );


// The domestic news section will be processed here
6. $ strQuery = "SELECT iNewsID, vcNewsTitle FROM tb_news_ch order by iNewsID DESC ";
$ Result = mysql_query ($ strQuery );
$ I = NUM;
7. while ($ row = mysql_fetch_array ($ result) & $ I> 0)
{
$ Array [] = array ("NewsID" => substr ($ row ["iNewsID"], 0, 40 ),
"NewsTitle" => substr ($ row ["vcNewsTitle"], 0, 40 ));

$ I --;
}
8. $ smarty-> assign ("News_CH", $ array );
9. unset ($ array );
Mysql_free_result ();


10. // process the international news section here
$ StrQuery = "SELECT iNewsID, vcNewsTitle FROM tb_news_in order by iNewsID DESC ";
$ Result = mysql_query ($ strQuery );
$ I = NUM;
While ($ row = mysql_fetch_array ($ result) & $ I> 0)
{
$ Array [] = array ("NewsID" => substr ($ row ["iNewsID"], 0, 40 ),
"NewsTitle" => substr ($ row ["vcNewsTitle"], 0, 40 ));

$ I --;
}
$ Smarty-> assign ("News_IN", $ array );
Unset ($ array );
Mysql_free_result ();


11. // The entertainment news section will be processed here
$ StrQuery = "SELECT iNewsID, vcNewsTitle FROM tb_news_mu order by iNewsID DESC ";
$ Result = mysql_query ($ strQuery );
$ I = NUM;
While ($ row = mysql_fetch_array ($ result) & $ I> 0)
{
$ Array [] = array ("NewsID" => substr ($ row ["iNewsID"], 0, 40 ),
"NewsTitle" => substr ($ row ["vcNewsTitle"], 0, 40 ));

$ I --;
}
$ Smarty-> assign ("News_MU", $ array );
Unset ($ array );
Mysql_free_result ();


Mysql_close ($ db );

// Compile and display the index. tpl template under./templates
12. $ smarty-> display ("index. tpl ");
?>


For convenience, I marked every place to be explained. The following describes the role of each part:

1. Program comments and style issues. I have added this to the program many times to help readers develop this habit.
2. File inclusion. This sentence means to include the Smarty class file into the current program file.
3. Constant definition: defines NUM as 5, which is the number of news entries
4. set the Smarty parameter: For more information about the parameters, see the previous section. Here, we only want to describe the $ smarty-> cache attribute. During the program debugging process, to set it to false, we can implement the program cache effect by designing it to true upon official release.
5. Database connection: do I have to say this part? Standard PHP statement.
6. Search for SQL statements in Chinese news: Standard SQL statements are sorted in descending order by new question numbers.
7. while ():
This statement controls the number of news lines to be displayed. first, assign a value to $ I as NUM, and NUM as a constant defined outside of the start. Use the $ I> 0 condition in the start judgment of while (), while () in each loop, the value of $ I is reduced by 1, so that when it completes five cycles, while will end.
Here we mainly look at the $ array [] array:
$ Array [] is theoretically a two-dimensional array, that is, the element in an array is another array. In the preceding example, when the while () statement ends, $ array is an array containing five array elements, and each element is an array of character indexes. these character indexes define the attribute value of $ news [loop] of the section loop block in the template. You must note that the attribute value corresponds to the attribute value of the template loop block, otherwise, it cannot be displayed!
When constructing this two-dimensional array, we use a substr () method to intercept characters. This method is for reference only. In actual use, because Chinese characters are full-width characters, using it may cause garbled characters. In future examples, we will use another netizen and the csubstr () function to implement the character truncation function.

8. Parse the section loop block of loop = $ News_CH in the template.
Note that when $ smarty-> assign ("News_CH", $ array) is used, the first parameter of assign is the value of loop in section, the second parameter is the array created above.

9. deregister $ array: $ array [] after use, it must be deregistered, because $ array is not cleared when a value is assigned to $ array using the value assignment statement, instead, the new array is added as an element of it. To avoid side effects, it is necessary to use unset () here.

10. International news processing module:
Like the domestic news processing module, you can compare the template with this section to find out what is related to it.

11. Entertainment news processing module: Same as above, we look for relationships among them. I believe you will have some gains after reading them.

12. Process and display index. tpl.


2. Next let's take a look at the source file of news. php:

News. php


<? Php

Include_once ("./comm/Smarty. class. php"); // contains the smarty class file
Define ("NUM", 5); // defines the number of news entries displayed each time.

$ Smarty = new Smarty (); // Create a smarty instance object $ smarty
$ Smarty-> templates_dir = "./templates"; // set the template directory
$ Smarty-> compile_dir = "./templates_c"; // Set the compilation Directory
$ Smarty-> cache_dir = "./cache"; // you can specify a cache directory.
$ Smarty-> cache_lifetime = 60*60*24; // you can specify the cache time.
$ Smarty-> caching = false; // set this parameter to false during debugging. Use true for release.
$ Smarty-> left_delimiter = "<{"; // you can specify the left boundary.
$ Smarty-> right_delimiter = "}>"; // you can specify the right boundary.


$ Db = mysql_connect ("localhost", "root", "") or die ("database connection error! ");
Mysql_select_db ("News", $ db );

$ NewsID = $ _ GET ["id"]; // Obtain the news id
$ NewsType = $ _ GET ["type"]; // The type of news to be displayed
Switch ($ NewsType)
{
Case 1:
$ DbName = "tb_news_ch ";
Break;
Case 2:
$ DbName = "tb_news_in ";
Break;
Case 3:
$ DbName = "tb_news_mu ";
Break;
}

$ StrQuery = "SELECT vcNewsTitle, ltNewsContent FROM $ dbName ";
$ Result = mysql_query ($ strQuery) or die ("database query error! ");
If ($ row = mysql_fetch_array ($ result ))
{
$ Smarty-> assign ("NewsTitle", $ row ["vcNewsTitle"]);
$ Smarty-> assign ("NewsContent", $ row ["ltNewsContent"]);

Mysql_free_result ($ result );
$ Smarty-> display ("news. tpl ");
}

Mysql_close ($ db );

?>


The above program statements about Smarty mainly have three rows:


PHP: [Copy to clipboard]
$ Smarty-> assign ("NewsTitle", $ row ["vcNewsTitle"]);
$ Smarty-> assign ("NewsContent", $ row ["ltNewsContent"]);

Mysql_free_result ($ result );

 

Simply replace NewsTitle and NewsContent on the news page with the content found in the database.

Well, the first part of the Smarty routine learning is here. I believe you will have a basic understanding of the usage of Smarty after learning it, the next section also uses this example to explain how to use the DB class in phplib to implement template control.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.