Smarty instance Teaching Example

Source: Internet
Author: User


Smarty instance Teaching Example (3. Using ADODB to connect to a 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 errors in the previous tutorial I wrote. Here, I would like to thank the nesta2001zhang brothers for finding outArticleSome errors. Otherwise, they will be

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, the effect of the first method is actually no different from that of the second method.ProgramI have already debugged,

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. Database execution written with standard SQL statementsCodeDuring database transplantation, you do not need to change the source program. 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
========================================================== ====================
<? 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
========================================================== ==================================
<? 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
========================================================== ======================================
<? 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.