Smarty instance teaching example

Source: Internet
Author: User
Smarty instance teaching example (3. use ADODB to connect to the database)

I have been busy for work for the first two months, so I didn't finish this tutorial in time. I don't have to work overtime on Saturday. I just need to leave it empty! When I started a new tutorial

First, modify some of the errors in the previous tutorial I wrote. here, I would like to thank the nesta2001zhang brothers for finding some errors in the article. Otherwise, they will be replaced by others.

Scold "mistaken children" (It's really embarrassing to say that, after my first draft was published, I found a lot of problems. later, some times I re-issued the modified files and encountered errors, really shouldn't

This ...)
In the previous tutorials:
========================================================== ========================
While ($ db-> next_record () & $ I> 0)
{
$ Array [] = array ("NewsID", csubstr ($ db-> f ("iNewsID"), 0, 20 ),
"NewsTitle", csubstr ($ db-> f ("vcNewsTitle"), 0, 20 ));

$ I --;
}
========================================================== ========================
It should be changed:
========================================================== ========================
While ($ db-> next_record () & $ I> 0)
{
$ Array [] = array ("NewsID" => $ db-> f ("iNewsID "),
"NewsTitle" => csubstr ($ db-> f ("vcNewsTitle"), 0, 20 ));

$ I --;
}
========================================================== ========================
Why? Because the second method is clearer and clearer, in fact, the effect of the first method is no different from that of the second method, and I have debugged these programs,

No problem.
Well, let's talk about ADODB today. when it comes to ADODB, ASP users may all know the ADO components on the WINDOWS platform, but the ADODB here is not the database operation of Microsoft.

As a component, but a set of database operation class libraries written by the php language. let's take a look at its advantages.
1. the database execution code written with standard SQL statements does not need to change the source program during Database transplantation. that is to say, it supports multiple databases, including ACCESS.
2. provide similar syntax functions to Microsoft ADODB. this is a good news for people switching from ASP to PHP. many of its operations are similar to ADODB in WINDOWS.
3. the two-dimensional array required by the Smarty loop can be generated, which simplifies the development of smarty. this will be demonstrated by me later.
4. supports database cache queries to increase the speed of database queries.
5. other practical functions.
Although there are many advantages, this class library is very huge, and its main execution class is only 107 K. Therefore, if you consider the execution efficiency, you should think about it carefully. but to be honest, its

The functions are still very powerful, and there are many very practical functions. using these functions can easily implement the functions we want. so when there are no special requirements for those bosses

Use it for defense

1. how to obtain ADODB? What is its runtime environment?
From http://sourceforge.net/project/show..w.hp4.0.5.
II. how to install ADODB?
Decompress the downloaded compressed file. note: the downloaded file format is adodb.tar.gz. this is a linux compression format. in windows, you can use winrar to import it.

Extract the directory and copy it to the adodb Directory of the specified directory. for example, I copied it to/comm/adodb/In the example.
3. how to call ADODB?
Use include_once ("./comm/adodb. inc. php"); isn't that necessary? The main file that contains ADODB.
4. how to use ADODB?
1. perform initialization:
ADODB uses a statement such as $ conn = ADONewConnection (); to initialize ADODB in two ways:
The first method is the traditional method. I will temporarily call it this name. The method used to create a new connection is similar to the standard connection method in php:
$ Conn = new ADONewConnection ($ dbDriver );
$ Conn-> Connect ($ host, $ user, $ passwd, $ db );
Simple? If you have used the db class in phplib, you should be familiar with it.

Method 2: Use the dsn method. in this way, the database connection statement is written as a statement for initialization. the dsn statement is written as: $ dsn =

"DBType: // User: Passwd @ Host/DBName"; DBType indicates the database type, User indicates the User name, Passwd indicates the password, Host indicates the server name, and DBName indicates the database name.

In this way, I use the oracle database, the username is oracleUser, the password is oraclePasswd, the database server is localhost, and the database is the dsn of oradb:
$ Dsn = "oracle: // oracleUserraclePasswd @ localhost/oradb ";
$ Conn = new ADONewConnection ($ dsn );
Programmers may be more interested in this method.

Both methods can be used, depending on your habits.

2. related concepts:
There are two basic classes for using ADODB. one is the ADOConnection class and the other is the ADORecordSet class. people who have used ASP will understand the meaning of these two classes,

ADOConnection refers to the database connection class, and ADORecordSet refers to the dataset class returned by the query statement executed by ADOConnection. you can query the relevant information of ADODB.

Class manual.

3. basic functions:

The methods related to the ADOConnection class are:
1. Connect: database connection method, which we have introduced above. For mysql, PConnect is also used in the same way as PHP.
2. Execute ($ SQL): an ADORecordSet class is returned when the query statement is executed.
3. GetOne ($ SQL): returns the first field of the first row.
4. GetAll ($ SQL): returns all data. This function is very useful. remember that when I write a news list input in a previous tutorial, I need to display it on the page.

Is the news list made into a two-dimensional array? The statement is as follows:
========================================================== ========================================================== =====
While ($ db-> next_record ())
{
$ Array [] = array ("NewsID" => $ db-> f ("iNewsID "),
"NewsTitle" => csubstr ($ db-> f ("vcNewsTitle"), 0, 20 ));
}
========================================================== ========================================================== =====
What does this line mean? Generate the news example table to be displayed.
$ Array [0] = array ("NewsID" => 1, "NewsTitle" => "The first article in the news ");
$ Array [1] = array ("NewsID" => 2, "NewsTitle" => "The second piece of news ");
...
This form, but if we do not need to control the title, we will be blessed in ADODB. we can write like this:
========================================================== ========================================================== =
$ StrQuery = "select iNews, vcNewsTitle from tb_news_ch ";
$ Array = & $ conn-> GetAll ($ strQuery); // pay attention to this statement.
$ Smarty-> assign ("News_CH", $ array );
Unset ($ array );
========================================================== ========================================================== =
Of course, $ conn should have been initialized. do you understand it? It turns out that the two-dimensional data that I want to manually create can be directly used GetAll here !!! This is also

Some people will say that ADODB + Smarty is one of the reasons for the invincible combination...
4. selectLimit ($ SQL, $ numrows =-1, $ offset =-1, $ inputarrr = false)

Statement, which has the same effect as the limit statement in mysql. here is a simple example:
$ Rs = $ conn-> SelectLimit ("select iNewsID, vcNewsTitle from tb_news_CH", 5, 1 );
Do you understand? $ Rs stores five records starting from the first record in the database. We know that the oracle database does not support limit in SQL statements, but if we

If ADODB is used, this problem will be easily solved!
5. Close (): Close the database. Although PHP will automatically Close at the end of the page, you must Close the database at the end of the page to complete the program.

The basic functions of ADORecordSet. ADORecordSet are as follows:
1. Fields ($ colname): return the value of the field.
2. RecordCount (): number of records included. this record determines the total number of records in the dataset.
3. getMenu ($ name, [$ default_str = ''], [$ blank1stItem = true], [$ multiple_select = false], [$ size = 0], [$ moreAttr = '']) very good one

Function. you can use this function to return a drop-down menu (or multiple selection boxes) with name = $ name )!!! Of course, it is an HTML string. this is an exciting good thing. $ name refers

The name attribute of option. $ default_str is the default selected string. $ blank1stItem indicates whether the first item is null, and $ multiple_select indicates whether multiple selection boxes exist.

After the string, you can use $ smarty-> ("TemplateVar", "GetMenuStr") to enter a drop-down list (or multi-first box) in "TemplateVar" of the template)
4. MoveNext (): Let's look at a piece of code:
========================================================== ========================
$ Rs = & $ conn-> Exceute ($ SQL );
If ($ rs)
{
While ($ rs-> EOF)
{
$ Array [] = array ("NewsID" => $ rs-> fields ["iNewsID"],
"NewsTitle" => csubstr ($ rs-> fields ["vcNewsTitle"]), 0, 20 );

$ Rs-> MoveNext ();
}
}
========================================================== ========================
Do you understand? Like the one in ms adodb!
5. MoveFirst (), MoveLast (), Move ($ to): Same. you can see what the function name means.
6. FetchRow (): return a row. check the code:
========================================================== ========================
$ Rs = & $ conn-> Exceute ($ SQL );
If ($ rs)
{
While ($ row = $ rs-> FetchRow ())
{
$ Array [] = array ("NewsID" => $ row ["iNewsID"],
"NewsTitle" => csubstr ($ row ["vcNewsTitle"]), 0, 20 );
}
}
========================================================== ========================
It implements the same functions as 4, but it seems to be more in line with PHP's habits, and 4 looks more like the ms adodb approach.

7. GetArray ($ num): returns the $ num row data in the dataset and combines it into a two-dimensional array. this method is used in index. php.

8. Close (): Same as mysql_free_result ($ rs); clear the occupied content.

Now, we will introduce the preliminary functions here. it is enough for us to use! In fact, ADODB also has many practical technologies, including formatting date and time, formatting query statements, and outputting tables.

You can view the manual by yourself.

Next we will start to learn about our program, which is also the Web program. I reorganized the comm directory and encapsulated the Smarty to improve the efficiency.

MySmarty. class. php is an encapsulated class that inherits from Smarty. Therefore, only the new class MySmarty will be called in all program files in the future. let's take a look at the directory structure:
+ Web (site root directory)

| ---- + Comm (Smarty Documentation Directory)

| ---- + Smarty (original Smarty file directory)
| ---- + Adodb (original directory of adodb)
| ----- MySmarty. class. php (expanded smarty file)
| ----- Csubstr. inc (Chinese characters are truncated)

| ---- + 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)

| ---- Newsbk, htm (original news page)

| ---- Index. php (Smarty homepage program file)

| ---- News. php (Smarty news display file)

| ---- NewsList. php (display news list)

| ------Example .txt (this document)

Compared with the previous two tutorials, the comm directory has been reorganized, and the structure of other files has not changed. compared with the previous two tutorials, only the comm directory and

Index. php and news. php, and added the news list. you can go to index. on the php execution page, click "domestic news", "International News", and "Entertainment News" to view their respective

For the news list, let's take a look at index. php:

========================================================== ====================
Index. php
========================================================== ====================
/*************************************** ******
*
* File name: index. php
* For use: Display instance programs
*
* Author: Master
* Email: teacherli@163.com
*
**************************************** *****/
Include_once ("./comm/mySmarty. class. php"); // An extension class file containing smarty
Include_once ("./comm/adodb. inc. php"); // contains the ADODB master execution file
Include_once ("./comm/csubstr. inc"); // contains the Chinese truncation class

Define ("NEWS_NUM", 5); // defines the number of news lists displayed.

$ Smarty = new MySmarty (); // Create a smarty instance object $ smarty

1. $ conn = ADONewConnection ("mysql"); // initialize ADODB
2. $ conn-> Connect ("localhost", "root", "", "News"); // Connect to the database


// The domestic news section will be processed here
3. $ strQuery = "SELECT iNewsID AS NewsID, vcNewsTitle AS NewsTitle FROM tb_news_CH order by iNewsID DESC ";
4. $ rs = & $ conn-> Execute ($ strQuery );
5. $ smarty-> assign ("News_CH", $ rs-> GetArray (NEWS_NUM ));
6. unset ($ rs );


// Process International News
$ StrQuery = "SELECT iNewsID AS NewsID, vcNewsTitle AS NewsTitle FROM tb_news_IN order by iNewsID DESC ";
$ Rs = & $ conn-> Execute ($ strQuery );
$ Smarty-> assign ("News_IN", $ rs-> GetArray (NEWS_NUM ));
Unset ($ rs );

// The entertainment news section will be processed here
$ StrQuery = "SELECT iNewsID AS NewsID, vcNewsTitle AS NewsTitle FROM tb_news_MU order by iNewsID DESC ";
$ Rs = & $ conn-> Execute ($ strQuery );
$ Smarty-> assign ("News_MU", $ rs-> GetArray (NEWS_NUM ));
Unset ($ rs );

7. $ conn-> close ();

// Compile and display the index. tpl template under./templates
$ Smarty-> display ("index. tpl ");
?>
========================================================== ============================================
Similarly, I add a number mark to the key point. The following describes their meanings:

1. create a connection object $ conn. it is important to note that it does not initially appear in the form of $ conn = new ADONewConnection ($ dbType), that is

, ADONewConnection is not a class, you cannot use new to initialize it. you will understand its source code. this is just a function.

2. you don't need to say that, do you? Open a News database. the host is localhost, the username is root, and the password is ""

3. for a query statement, note that the queried fields must be re-identified using the AS keyword. The name is the name of the template variable you set in the template.

4. Execute is used to Execute this query. a RecordSet dataset is returned.

5. here is a method: $ rs-> GetArray ($ num), which is described above. it returns the $ num row from the $ rs dataset, the result is a two-dimensional number that can be recognized by Smarty.

As a result, ADODB automatically builds such a structure for us. In our previous examples, we used a loop to construct such an array.

6. I don't need to mention this sentence?

7. Disable memory-related resources.

You can see that there are no while statements in the entire program, and the overall structure of the program is very clear. This is why ADODB + Smarty is a golden combination.

The answer is simple and simple. I don't know if you have thought about it. here we have no control over the length of the displayed News title. that is to say, if the length of a News title exceeds the length of a line

If the layout is broken down to the next line, the layout will be broken down. let's decide whether to use the layout as appropriate, you can also use an intermediary like the previous section

Then, use a circular statement to reconstruct the two-dimensional array and make it fit your purpose. let's think about it by yourself. refer to the practice in PHPLIB, I have introduced...

Let's take a look at the news page.

========================================================== ==================================
News. php
========================================================== ==================================
/*************************************** ******
*
* File name: news. php
* For use: news Display program
*
* Author: Master
* Email: teacherli@163.com
*
**************************************** *****/
Include_once ("./comm/mySmarty. class. php"); // An extension class file containing smarty
Include_once ("./comm/adodb. inc. php"); // contains the ADODB master execution file

$ Smarty = new MySmarty (); // Create a smarty instance object $ smarty

$ Conn = ADONewConnection ("mysql"); // initialize ADODB
$ Conn-> Connect ("localhost", "root", "", "News"); // Connect to the database

$ 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 AS NewsTitle, ltNewsContent AS NewsContent FROM". $ dbName;
1. $ row = & $ conn-> GetRow ($ strQuery); // returns a one-dimensional array with the subscript as the template variable name.

$ Smarty-> display ($ row );
Unset ($ row );

$ Conn-> Close ();
?>
========================================================== ==================================
The key point is that there is only one local value in news. php.

1. $ conn-> GetRow ($ strQuery): returns a one-dimensional array in the following format:

$ Array = ("NewsTitle" => "xxxx", "NewsContent" => "yyyyy ...")
Do you understand what smarty will do after $ Smarty ($ array? By the way, it is equivalent:
$ Smarty-> assign ("NewsTitle", "xxxx ");
$ Smarty-> assign ("NewsContent", "yyyyy ...");

Simple. it's really easy.

Next let's take a look at the news list:
========================================================== ======================================
NewsList. php
========================================================== ======================================
/*************************************** ******
*
* File name: newsList. php
* For use: news list display program
*
* Author: Master
* Email: teacherli@163.com
*
**************************************** *****/
Include_once ("./comm/mySmarty. class. php"); // An extension class file containing smarty
Include_once ("./comm/adodb. inc. php"); // contains the ADODB master execution file

$ Smarty = new MySmarty (); // Create a smarty instance object $ smarty

$ Conn = ADONewConnection ("mysql"); // initialize ADODB
$ Conn-> Connect ("localhost", "root", "", "News"); // Connect to the database

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

$ StrQuery = "SELECT iNewsID AS NewsID, vcNewsTitle AS NewsTitle FROM". $ tbName;
1. $ rs = & $ conn-> GetAll ($ strQuery );
2. $ smarty-> assign ("NewsType", $ NewsType); // This sentence serves the link in the news list
3. $ smarty-> assign ("NewsList", $ rs );
Unset ($ rs );
$ Conn-> close ();

$ Smarty-> display ("newsList. tpl ");
?>
========================================================== ======================================
Here is a description:

1. GetAll ($ strQuery): This function is a good function. it combines all the data queried by $ strQuery into a two-dimensional array that can be recognized by Smarty,

Remember: it returns a two-dimensional array instead of a RecordSet. you can directly use it in three places in the program.
2. this is done to GET the parameter type = XX when linking news headlines.

Postscript:
Note the following when using ADODB:
1. initialization: the initialization method is not to use new because it is not an object.
2. method: Basically, each method is a mix of names starting with an uppercase or lowercase letter, which seems to be different from * NIX's habits and also different from PHP's overall style.

Note the case sensitivity.

Well, this Smarty series of tutorials has basically been completed here. I hope more experts will write more experiences.

Improve together! Because the company is not allowed to open QQ, if you want to communicate with me, please add me MSN: teacherli@ceua.org, welcome to discuss together!

(Source: Viphot)

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.