The title of the news page to display is displayed as the news title "---- Tianjiao Information Network"
2. News headline:
<{$ newstitle}> div>
Here is a template variable $ newstitle, meaning. PHP replaces $ newstitle to the title of current news in the database.
3. News content:
<{$ newscontext}> p>
This sentence is also easy to display news content in the current location.
Of course, it is just simple to list the news, you can also list the article, publish the time, author, and related news when practical applications, and discuss it here.
Third, the program part:
1. Let's take a look at the source file of index.php, then let's take another step by analyze its role:
============================================================================================================================================================================================================= ===========
Index.php
============================================================================================================================================================================================================= =========== PHP
1. /*********************************************
*
* File name: index.php
* Decision: Display instance program
*
* Servers: Master
* Email:
Teacherli@163.com
*
*************************************************** /
2. INCLUDE_ONCE ("./ Comm / Smarty.class.php"); // contains the Smarty class file
3. Define ("num", 5); // Define the number of news entries each displayed
4. $ smarty = new smarty (); // Create a smarty instance object $ smarty
$ Smarty-> Templates_Dir = "./Templates"; // Settings Template Directory
$ smarty-> compile_dir = "./Templates_c"; // Set the compilation directory
$ smarty-> cache_dir = "./cache"; // Set the cache directory
$ smarty-> cache_lifetime = 60 * 60 * 24; // Set the cache time
$ Smarty-> Caching = false; // This is set to false when debugging, please use true when publishing
$ Smarty-> LEFT_DELIMITER = "<{"; // Set the left boundary
$ Smarty-> Right_Delimiter = "}>"; // Set the right border
5. $ db = mysql_connect ("localhost", "root", "");
MySQL_SELECT_DB ("News", $ db);
// This will be dealt with the domestic news section
6. $ strQuery = "select inewsid, inewstitle 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. // Treat the International News section
$ strQuery = "select inewsid, inewstitle from tb_news_in order by inewsid desc"; $ results = 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. // This section will be dealt with the entertainment news
$ STRQUERY = "SELECT INEWSID, INEWSTITLE 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");
?>
In order to facilitate explanation, I labeled every place to be explained, and it will be said to have the role of each part:
1. Program annotation, style problem, I have multiple times in the program to make readers to develop this habit.
2. The file is included. This sentence means containing the class file of Smarty to the current program file.
3. Constant definition: Define NUM to 5, the number of news display
4. Set the smarty parameter: About the parameters inside, you can refer to the previous section, here only want to specify $ smarty-> cache properties, during our program debugging process, set it to false, officially released When you design it to true, you can implement our program cache effect.
5. Database connection: I don't have to say this part? Standard PHP statement.
6. During the domestic news search SQL statement: Standard SQL statement, order sequencing in order numbers.
7. While ():
This sentence controls the number of news rows to be displayed. First, give $ I Num, NUM for us a constant defined outside, use $ I> 0 conditions at the start judgment of While (), while () each time The value of $ i should be reduced when the cycle is cycled, so that when it completes 5 cycles, the while will end.
Here we mainly take a look at $ array [] This array:
$ rail [] is theoretically a two-dimensional array, that is, an element in an array is another array. In the above example, when the while () statement ends, $ array is an array containing 5 array elements, Each element is an array of characters indexes. And these character indexes are the property values of the $ news [loop] defined in the template. Everyone must pay attention to the attribute value of the template cycle block. Otherwise, it will not be displayed!
When building this two-dimensional array, we use a substr () method for character interception. This method is here for reference only. In actual use because Chinese is a full-horn character, it may cause garbled when using it, in the later example in the examples Another netizen will use the CSUBSTR () function to implement the character interception function. 8. Resolution of the section cycle block in the template's loop = news_ch.
Everyone should pay attention to using $ smarty-> assign ("news_ch", $ array), ASSIGN's first parameter is the value of LOOP in section, and the second parameter is the array established above.
9. Log out $ ARRAY: $ array [] After using it, you will not be emptied when you use the assignment statement to assign $ array, but the new array is increased as an element of it, in order not to produce side effects, It is necessary to use unset () here.
10. International News Processing Module:
Like domestic news processing modules, you can compare the template and this paragraph, find what is related to what is related.
11. Entertainment News Process Module: I have the same, everyone finds the relationship. I believe that everyone will have harvested.
12. Process and display index.tpl.
2. Let's take a look at the source file of News.php:
============================================================================================================================================================================================================= ======
News.php
============================================================================================================================================================================================================= ======
PHP
/ ***************************************************
*
* File name: news.php
* Job: News display
*
* Servers: Master
* Email:
Teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / Smarty.class.php"); // contains the smarty file
Define ("NUM", 5); // Defines the number of news bars each displayed
$ smarty = new smarty (); // Establish a smarty instance number $ smarty
$ Smarty-> Templates_Dir = "./Templates"; // Settings Template Directory
$ smarty-> compile_dir = "./Templates_c"; // Set the compilation directory
$ smarty-> cache_dir = "./cache"; // Set the cache directory
$ smarty-> cache_lifetime = 60 * 60 * 24; // Set the cache time
$ Smarty-> Caching = false; // This is set to false when debugging, please use True $ Smarty-> Left_DELIMITER = "<{"; // set the left boundary character when publishing.
$ Smarty-> Right_Delimiter = "}>"; // Set the right border
$ db = mysql_connect ("localhost", "root", "") or Die ("Database Connection Error!");
MySQL_SELECT_DB ("News", $ db);
$ Newsid = $ _get ["id"]; // Get news numbers
$ Newstype = $ _get ["type"]; // to display the type of news
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;
$ results = mysql_query ($ strquery) or Die ("Database Query!");
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);
?>
This is only 3 lines about Smarty's program statement:
============================================================================================================================================================================================================= ================
$ Smarty-> Assign ("NewStitle", $ ROW ["Vcnewstitle"]);
$ Smarty-> Assign ("NewsContent", $ ROW ["LTNewsContent"]);
MySQL_Free_Result ($ Result);
============================================================================================================================================================================================================= ================ It is very simple to replace newstitle in the news page to find the content you are looking for from the database.
Ok, the primary part of this SMARTY routine learning is here, I believe that everyone will have a basic understanding of Smarty after learning, and the next section also uses this example to talk about how to use phplib. The DB class is to implement control of the template.
============================================================================================================================================================================================================= ========================================
SMARTY instance tutorial example articles (II, using phplib's DB class)
A few days ago, this example has been written today, why do you want to take the db class in phplib? Many people are learning PHP, the template that may first come first is PHPLIB. The reason is very simple: Many PHP learning materials are introduced to phplib. When PHPLIB is very hot, one is that it is not implemented in PHP3. SESSION features, until now there are still many people using phplib template technology because it is very simple. At the same time, the database operation class on phplib also has a small file, and the loading speed is fast.
. I like its syntax, I feel very close to mySQL statement in PHP. Ok, there is not much nonsense, come see our procedure. The program also said in the site of the instance. About the establishment of the database and the establishment of the template, please refer to the introduction of the next section, mainly introducing the newly added to the program. Let's see the catalog table first:
Web (Site root directory)
|
| ---- Comm (Smarty Related Document Directory)
| | |
| | ---- Plugins (Smarty Plugin Directory)
| | ----- Config_File.class.php (Smarty Profile)
| | ----- Smarty.class.php (Smarty Primary File)
| | ----- Smarty_Compiler.class.php (Smarty Compile "
| | ----- DB_MYSQL.Inc.php (db class in phplib)
| | ----- csub.inc.php (a function of intercepting Chinese)
|
| ---- Cache (Smarty Cache Directory, * NIX to ensure read and write permissions) |
| ---- Templates (Site Template File Save Directory)
| | |
| | ---- Header.tpl (Page Tablet Template File)
| | ---- Index.tpl (Site Home Template File)
| | ---- Foot.TPL (Page Foot Template File)
| | ---- News.tpl (News page template file)
|
|
| ---- Templates_c (save the catalog after the template file, * NIX guarantees read and write permissions)
|
| ---- CSS (Site CSS Directory)
|
| ---- Image (Site Picture Directory)
|
| ---- Media (Site Flash Animation Storage Directory)
|
| ---- IndexBak.htm (Home Original Render]
|
| ---- NewsBak, HTM (News page Original effect)
|
| ---- Index.php (Smarty Home Program File)
|
| ---- News.php (Smarty News Display File)
|
| ---- routine description .txt (this document)
Here mainly in the / commit / directory, one is db_mysql.inc.php, which is called DB_MYSQL.INC in phplib, and the Inc file is displayed directly from the browser by default. In the device, so for security we change its extension to db_mysql.inc.php; the second file is a function that contains intercept Chinese characters.
CSUBSTR (), when we use it, we display its source code.
Here first, the main member variables of DB_SQL defined in db_mysql.inc.php will give you a brief introduction to everyone:
First, member variables:
1. $ Host: Host Name
2. $ Database: Database Name
3. $ user: Username
4. $ Password: Password
Second, member functions:
1. Connect ($ Database = ", $ Host =" ", $ user =", $ password = ""): Establish a connection, return to the connection ID
2. Query ($ query_string): Inquiry, return to the query ID
3. Free (): Release the current query ID resource
4. Next_Record (): Return to the next return set
5. Num_Rows (): The number of data lines in the current query number
6. f ($ name): The value of the current field
Other functions are basically not used in our procedures, so they don't introduce, interested readers can view relevant information themselves.
PHP code: ----------------------------------------------- ---------------------------------
INDEX.TPL in Templates and News.tpl with the previous section, different only in Index.php and News.tpl, first take a look at INDEX.PHP:
================================
Index.php
================================
PHP
/ ******************************************************
* File name: index.php
* Decision: Display instance program
*
* Servers: Master
* Email:
Teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / Smarty.class.php"); // contains the smarty file
1. / / =======================================
INCLUDE_ONCE ("./ Comm / DB_MYSQL.Inc.php"); / / contains database operation classes
INCLUDE_ONCE ("./ Comm / Csubstr.inc"); // Contains Chinese Intercept class
/ / ===============================================================================================================================================================================
Define ("NUM", 5); // Defines the number of news bars each displayed
$ smarty = new smarty (); // Establish a smarty instance number $ smarty
$ Smarty-> Templates_Dir = "./Templates"; // Settings Template Directory
$ smarty-> compile_dir = "./ Templates_c"; // Set the compilation directory
$ smarty-> cache_dir = "./cache"; // Set the cache directory
$ Smarty-> Caching = false; // This is set to false when debugging, please use true when publishing
$ Smarty-> LEFT_DELIMITER = "<{"; // Set the left boundary
$ Smarty-> Right_Delimiter = "}>"; // Set the right border
2. $ db = new db_sql (); / / instantiate a DB class
$ dB-> host = "localhost"; // database host name
$ db-> database = "news"; // database name
$ dB-> user = "root"; // user name
$ db-> password = ""; // password
$ db-> connet (); // Database connection
// This will be dealt with the domestic news section
$ strquery = "select inewsid, inewstitle from tb_news_ch order by inewsid desc";
3. $ db-> query ($ strquery);
$ I = NUM;
4. While ($ db-> next_record () && $ i> 0)
{
5. $ array [] = array ("newsid", csubstr ($ db-> f ("inewsid"), 0, 20), "newstitle", csubstr ($ db-> f ("vcnewstitle", 0, 20));
$ I -;
}
$ Smarty-> Assign ("News_CH", $ Array);
UNSET ($ array);
6. $ db-> free ();
// Treat the international news section
$ strQuery = "select inewsid, inewstitle from tb_news_in order by inewsid desc";
$ dB-> query ($ strquery);
$ I = NUM;
While ($ db-> next_record () && $ i> 0)
{
$ array [] = array ("newsid", csubstr ($ db-> f ("inewsid"), 0, 20),
"Newstitle", CSUBSTR ($ db-> f ("vcnewstitle"), 0, 20));
$ I -;
}
$ Smarty-> Assign ("News_IN", $ Array);
UNSET ($ array);
$ dB-> free ();
// Here you will process the entertainment news part
$ STRQUERY = "SELECT INEWSID, INEWSTITLE from TB_NEWS_MU ORDER BY INEWSID DESC";
$ dB-> query ($ strquery);
$ I = NUM;
While ($ db-> next_record () && $ i> 0)
{
$ array [] = array ("newsid", csubstr ($ db-> f ("inewsid"), 0, 20),
"Newstitle", CSUBSTR ($ db-> f ("vcnewstitle"), 0, 20));
$ I -;
}
$ Smarty-> Assign ("News_MU", $ Array;
UNSET ($ array);
$ dB-> free ();
// Compile and display the INDEX.TPL template under ./Templates
$ Smarty-> Display ("INDEX.TPL");
?>
Old rules, I added a label for key places to see these places:
1. Here is to include the db_sql class file, the following line is to include a Chinese intercept class to the current page
2. Instantiate a class and set the Host, Database, User, Password property of the class, last Connect database
3. Call $ DB-> Query ($ STRQUERY) for a data query
4. $ db-> next_record () Read the next line of the database query return value (Note: Call Query () Returns the first record of the first record of the data set)
5. csubstr () is a Chinese intercept class we use, the source file of the class is as follows:
============================================================================================================================================================================================================= === csubstr.inc.php
============================================================================================================================================================================================================= ===
6. $ db-> free (): Release the current query back resources
Ok, use the class for database operation, you can improve the program's readability, and it is also convenient for the operation of the database.
Next, let's take a look at News.php:
================================================================================★
News.php
================================================================================★
PHP
/ ***************************************************
*
* File name: news.php
* Job: News display
*
* Servers: Master
* Email:
Teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / Smarty.class.php"); // contains the smarty file
/ / ===============================================================================================================================================================================
INCLUDE_ONCE ("./ Comm / DB_MYSQL.Inc.php"); / / contains database operation classes
INCLUDE_ONCE ("./ Comm / Csubstr.inc"); // contains Chinese intercept classes / / ============================= ==========
Define ("NUM", 5); // Defines the number of news bars each displayed
$ smarty = new smarty (); // Establish a smarty instance number $ smarty
$ Smarty-> Templates_Dir = "./Templates"; // Settings Template Directory
$ smarty-> compile_dir = "./ Templates_c"; // Set the compilation directory
$ smarty-> cache_dir = "./cache"; // Set the cache directory
$ smarty-> cache_lifetime = 60 * 60 * 24; // Set the cache time
$ Smarty-> Caching = false; // This is set to false when debugging, please use true when publishing
$ Smarty-> LEFT_DELIMITER = "<{"; // Set the left boundary
$ Smarty-> Right_Delimiter = "}>"; // Set the right border
$ dB = new db_sql (); // instantiate a DB class
$ dB-> host = "localhost"; // database host name
$ db-> database = "news"; // database name
$ dB-> user = "root"; // user name
$ db-> password = ""; // password
$ db-> connet (); // Database connection
$ Newsid = $ _get ["id"]; // Get news numbers
$ Newstype = $ _get ["type"]; // to display the type of news
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;
1. $ db-> query ($ strquery);
2. IF ($ db-> next_record ())
{
$ Smarty-> Assign ("NewStitle", $ db-> f ("vcnewstitle"));
$ Smarty-> Assign ("NewsContent", $ db-> f ("ltnewscontent");
$ dB-> free ();
$ Smarty-> Display ("news.tpl");
Else
{
Echo "No News Content";
}
?>
Everyone can take a look at 1, 2, is it simpler than the original mysql function directly?
If you are excess, don't say much, if you have seen the previous example seriously, then this article should be very well understood.
======================
postscript:
The template part I basically spended some of the examples in the manual, and the actual essence is part of the program design part. If you want to learn it, I have to see two cases, I put two routines and previous mentioned The sample program is placed in three packaging files, tested by "Shenxian Sister", everyone can debug while watching.
Here is 3 examples, I pack them together.
SMARTY program example .rar
============================================================================================================================================================================================================= ========================================
SMARTY instance teaching instance articles (three, using the AdoDB connection database)
The first two months have been very busy because of the work of the work, so don't complete this tutorial in time, just don't have to work overtime today, take an empty completed it! When you start the new tutorial, I
First modify some of the mistakes in the tutorial you wrote, I would like to thank Nesta2001zhang brothers, he found some mistakes in the article, otherwise it was really
"The wrong child" (said it is really embarrassing, my first draft is released afterwards, and I found a lot of questions, and then there was a mistake in the document after returning to revisions, really should not
This ...)
In the previous tutorial:
============================================================================================================================================================================================================= =======
While ($ db-> next_record () && $ i> 0)
{
$ array [] = array ("newsid", csubstr ($ db-> f ("inewsid"), 0, 20),
"Newstitle", CSUBSTR ($ db-> f ("vcnewstitle"), 0, 20));
$ I -;
}
============================================================================================================================================================================================================= ======= should be changed to:
============================================================================================================================================================================================================= =======
While ($ db-> next_record () && $ i> 0)
{
$ array [] = array ("newsid" => $ db-> f ("inewsid"),
"Newstitle" => csubstr ($ db-> f ("vcnewstitle"), 0, 20));
$ I -;
}
============================================================================================================================================================================================================= =======
Why don't you change this? Because the second method is clearer, it is more clear. It is actually the effect of the first way and the second method is not different, and I have been debugged with the few programs.
There is no problem.
Ok, then we will talk about AdoDB today, say adoDB, you may have an ASP know the ADO components of the Windows platform, but our adodb is not Microsoft's database.
As a component, but a set of database operations class libraries written in the PHP language, let's take a look at what is the advantage of it.
1. Database execution code written in a standard SQL statement does not have to change the source when performing database transplantation, that is, it supports multiple databases, including Access.
2. Provide similar syntax features similar to Microsoft AdoDB. This is a great gospel for people from ASP to PHP, and many of its operations are similar to ADODB in Windows.
3. You can generate the two-dimensional array of Smarty cycles, which simplifies smarty development. This is the wait for me to give you a demonstration.
4. Support the database's cache query, the most likely to improve the speed of the query database.
5. Other practical features.
Although there are many advantages, because this library is very large, it is 107K, so if you consider the efficiency, you must think about it. But to be honest, its
The function is still very powerful, there are a lot of practical features, using it, it can be very convenient to implement the features we want. So everyone does not have special requirements for those bosses
Use
First, how to get adoDB? What is its operating environment?
From http://sourceforge.net/project/show ... 簆 HP4.0.5 or more. Second, how to install ADODB?
Unzip the underlying compressed file, pay attention: Everyone downloads back format is adoDb.tar.gz, this is Linux's compression format, you can use WinRAR to enter in Windows.
Under the completion of the decompression, copy the directory to the AdoDB directory of the specified directory, copy it to / comm / adoDB / in the example.
Third, how to call AdoDB?
Use incrude_once ("./comm/adodb/adodb.inc.inc.php"); don't say it? Contains the main file of AdoDB.
Fourth, how to use AdoDB?
1. Perform initialization:
AdoDB uses $ conn = adonewconnection (); this statement is initialized, and there are two ways to initialize AdoDB:
The first way is: Traditional ways. I temporarily called it for this name. It is used to create a new connection method like a standard connection in PHP:
$ conn = new adonewconnection ($ dbdriver);
$ conn-> Connect ($ Host, $ User, $ Passwd, $ dB);
Simple? If you use the DB class in phplib, you should be familiar with it.
The second way: uses the DSN mode, which is written to a statement to initialize the connection statement of the database. The writing of the DSN is: $ dsn =
"Dbtype: // user: passwd @ host / dbname"; where dbtype indicates database type, user names, passwd is password, Host is server name, dbname is the database name
Like this, I use Oracle Database, User Name: Oracleuser, Password to OraclePasswd, Database Server to Localhost, Database to ORADB DSN Words:
$ DSN = "Oracle: // OracleUserraclepasswd @ localhost / oradb";
$ conn = new adonewconnection ($ DSN);
This approach may be more interested in programmers coming from ASP.
These two ways can be used, to see personal habits.
2. Related concepts:
There are two basic classes using AdoDB, one is the Adoconnection class, the other is the AdoCordset class, people who have used ASP see that these two classes will understand its meaning,
AdoConnection refers to the class of database connections, and the adorecordset refers to the data set by AdoConnection to perform query statements. The relevant information can be queried by AdoDB
Class manual.
3. Basic functions:
About the relevant methods of the Adoconnection class are:
1.Connect: Database connection method, we introduced it. There is also a PConnect for mysql, just like the usage in the PHP language.
2.Execute: The result of the execution query statement is returned to an Adorecordset class.
3.Getone ($ SQL): Returns the first field of the first line
4.Getall ($ SQL): Returns all data. This function is a big use, remember that I will need to write on the page when I write about the news list in the previous tutorial.
News list makes a two-dimensional array? Is this statement:
============================================================================================================================================================================================================= ========================================== WHILE ($ db-> next_record ())
{
$ array [] = array ("newsid" => $ db-> f ("inewsid"),
"Newstitle" => csubstr ($ db-> f ("vcnewstitle"), 0, 20));
}
============================================================================================================================================================================================================= ====================================
What does this line mean? It is the news example that will be displayed.
$ array [0] = array ("newsid" => 1, "newstitle" => "The first article here");
$ array [1] = array ("newsid" => 2, "newstitle" => "Article 2 of the news");
...
In this form, but if we don't need to control the title, we are blessed in AdoDB, we can write this:
============================================================================================================================================================================================================= ========================================= $ strQuery = "SELECT INEWS, VCNEWSTITIL AU"; "
$ array = & $ conn-> getAll ($ strquery); // Note this statement
$ Smarty-> Assign ("News_CH", $ Array);
UNSET ($ array);
============================================================================================================================================================================================================= =======================================================================================================================================================
Of course, $ conn here should be initialized, I don't know if you understand? It turns out that the two-dimensional data created by hand is using getAll directly! ! ! This is also
What some people will say Adodb Smarty is one of the causes of invincible combination ...
4.SelectLimit ($ SQL, $ NumRows = -1, $ OFFSET = -1, $ INPUTARRR = FALSE): Return to a dataset, everyone is not difficult to see from the statement it is a limited query language
Sentence, with LIMIT in the mysql statement, there is a simple example, come to a simple example:
$ r = $ conn-> selectlimit ("Select inewsid, vcnewstitle from tb_news_ch", 5, 1);
do you understand? Saved in $ RS is 5 records from the first record in the database. We know that in the Oracle database does not support using Limit in the SQL statement, but if we make
With AdoDB, then this problem is easy to solve!
5.Close (): Turn off the database, although PHP is automatically turned off at the end of the page, but for the full point of the program, the database is turned off on the page.
About AdorecordSet.Adorecordset is the result of $ conn-> execute ($ SQL), its basic functions are as follows:
1. Fields ($ colname): Returns the value of the field.
2. RecordCount (): The number included. This record determines the total number of records of the data set .3. GetMenu ($ name, [$ default_str = '), [$ blank1stItem = true], [$ multiple_select = false], [$ size = 0], [$ moreattr = '']) Very good one
Function, use it to return a name = $ name drop-down menu (or multiple box) !!! Of course, it is a html string, this is an exciting good thing, $ name refers to
Option's Name property, $ default_str is a string selected by default, $ blank1stitem points out whether the first item is empty, $ multiple_select points to whether it is a multi-selection box, and we get this
After the strings, you can use $ Smarty -> ("Templatevar", "GetMenustr") to enter a drop-down list at the TemplateVar (or more box)
4. MoveNext (): To see a code:
============================================================================================================================================================================================================= =======
$ r = & $ conn-> exceuters;
IF ($ r)
{
While ($ RS-> EOF)
{
$ array [] = array ("newsid" => $ rs-> fields ["inewsid"],
"Newstitle" => csubstr ($ RS-> Fields ["vcnewstitle"]), 0, 20);
$ r-> movelnext ();
}
}
============================================================================================================================================================================================================= =======
Understand? Very like MS AdoDB!
5. MoveFirst (), Movese (), Move ($ to): The same, see what the function is named, you can know what it means.
6. fetchrow (): Return to a row, see the code:
============================================================================================================================================================================================================= =======
$ r = & $ conn-> exceute ($ sql); if ($ r)
{
While ($ row = $ r-> fetchrow ())
{
$ array [] = array ("newsid" => $ row ["inewsid"],
"Newstitle" => csubstr ($ row ["vcnewstitle"], 0, 20);
}
}
============================================================================================================================================================================================================= =======
It achieves the same functionality as 4, but it seems to be a habit of PHP, and 4 habits look more like MS AdoDB.
7.GetArray ($ NUM): Returns the $ NUM line data in the data set, combines it into two-dimensional arrays. This method we are in an example index.php.
8. Close (): With mySQL_FREE_RESULT ($ RS); clearing the content is occupied.
Ok, the initial function is introduced here, we use it! In fact, AdoDB has many practical technology, including formatting date, format query statement, output form, more advanced
Point cache query, with query, etc., you can view the manual yourself.
Below we are beginning to learn our procedures, the same still the web program, I will reorganize it, and in order to improve the efficiency to add SMARTY.
MySMARTY.CLASS.PHP is a packaged class, which inherits from smarty, so only new class mysmarty is called in all program files, first to see the directory structure:
Web (Site root directory)
|
| ---- Comm (Smarty Related Document Directory)
| | |
| | ---- Smarty (Smarty Original Directory)
| | ---- AdoDB (AdoDB Original Directory)
| | ----- mysmarty.class.php (SMARTY file after the extended)
| | ----- Csubstr.inc (intercepting Chinese characters)
|
| ---- cache (Smarty Cache Directory, * NIX to ensure read and write permissions)
|
| ---- Templates (Site Template File Save Directory)
| | |
| | ---- Header.tpl (Page Tablet Template File)
| | ---- Index.tpl (Site Home Template File)
| | ---- Foot.TPL (Page Foot Template File)
| | ---- News.tpl (News page template file)
|
|
| ---- Templates_c (save the catalog after the template file, * NIX guarantees read and write permissions)
|
| ---- CSS (Site CSS Directory)
|
| ---- Image (Site Picture Directory)
|
| ---- Media (Site Flash Animation Storage Directory)
|
| ---- IndexBak.htm (Home Original Render]
|
| ---- NewsBak, HTM (News page Original effect)
|
| ---- Index.php (Smarty Home Program File)
|
| ---- News.php (Smarty News Display File)
|
| ---- NewsList.php (Show news list)
|
| ---- routine description .txt (this document)
Compared to the top two tutorials, there is no change in the Comm-directory, and the other file structures do not change. The entire site is relatively two tutorials, and the changed place has only a Comm-directory and index.php and news.php, Added a list of newsletters, you can click "Domestic News", "International News", "Entertainment News", and "Entertainment News" to view the respective "domestic news", "International News", "Entertainment News" in the "Domestic News", "Entertainment News" after INDEX.PHP execution.
News list, let's take a look at INDEX.PHP:
============================================================================================================================================================================================================= ====
Index.php
============================================================================================================================================================================================================= ====
PHP
/ ***************************************************
*
* File name: index.php
* Decision: Display instance program
*
* Servers: Master
* Email: teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / MySmarty.class.php"); // contains Smarty's extended class file
INCLUDE_ONCE ("./ Comm / AdoDB / AdoDb.inc.PHP"); / / contains the AdodB main execution file
INCLUDE_ONCE ("./ Comm / Csubstr.inc"); // Contains Chinese Intercept class
Define ("news_num", 5); // Defines the number of news lists
$ smarty = new mysmarty (); // Establish a smarty instance object $ smarty
1. $ conn = adonewconnection ("mysql"); // Initialize AdoDB
2. $ conn-> Connect ("LocalHost", "root", "" ""); / / Connect the database
// This will be dealt with the domestic news section
3. $ strQuery = "SELECT INEWSID AS NEWSID, VCNEWSTILE AS NEWSID, VCNEWSTILE AS NEWSTILE,"
4. $ r = & $ conn-> execute ($ strquery);
5. $ Smarty-> Assign ("news_ch", $ r -> getArray (news_num));
6. Unset ($ RS);
// Treat the international news section
$ strQuery = "select inewsid as newsid, vcnewstitle as newstitle from tb_news_in order by inewsid desc"; $ = & $ conn-> execute ($ strquery);
$ Smarty-> Assign ("News_IN", $ RS-> GetArray (news_num));
UNSET ($ RS);
// Here you will process the entertainment news part
$ STRQUERY = "SELECT INEWSID AS NEWSID, VCNEWSTILE AS NewStitle from TB_News_Mu Order By inewsid";
$ r = & $ 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 added a number in key places, let's explain their meaning:
1. Create a connection object $ conn, everyone should pay attention to it is that its initial is not in the form of $ conn = new adonepnection ($ dbtype), that is,
AdonewConnection is not a class, you can't initialize it with New. Look at its source code you will understand, this is just a function.
2. Don't say this? Open a new database, the host is: localhost, the username root, the password is ""
3. A query statement, pay attention, here you want to use the field of the query using the AS keyword to re-identify, named the name of the template variable you set in the template.
4. Use Execute to perform this query, and return a Recordset dataset
5. Here is a method: $ RS-> GetArray ($ NUM) This is introduced on the top, it is to return $ NUM line from the data set of $ RS, resulting in a two-dimensional number identified by smarty
According to this, ADODB automatically constructs such a structure, and in our previous example, it is used to build such an array using a loop.
6. I don't have to say this this sentence?
7. Turn off the relevant resources in memory.
Everyone can see what the While statement does not appear in the entire program, the overall structure of the program is very clear, this is why AdoDB Smarty is the reasons for gold combination. But
Said back, simple and simple questions, I don't know if you think about it, there is no control on the length of the news title shown, that is, if a news title is exceeded by the line
Wai, it is automatically folded to the next line, then the entire layout will mess, said that everyone has made this situation to decide whether to use this, you can also use a mediation in the previous section.
As, use a circular statement to reconstruct this two-dimensional array, so that it meets your use, how to do yourself, refer to PHPLIB, I introduced the next section ... Let's take a look at the news page Bar
============================================================================================================================================================================================================= ===========
News.php
============================================================================================================================================================================================================= ===========
PHP
/ ***************************************************
*
* File name: news.php
* Job: News display
*
* Servers: Master
* Email: teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / MySmarty.class.php"); // contains Smarty's extended class file
INCLUDE_ONCE ("./ Comm / AdoDB / AdoDb.inc.PHP"); / / contains the AdodB main execution file
$ smarty = new mysmarty (); // Establish a smarty instance object $ smarty
$ conn = adonewconnection ("mysql"); // Initialize AdoDB
$ conn-> connect ("localhost", "root", "" ""); // Connect the database
$ Newsid = $ _get ["id"]; // Get news numbers
$ Newstype = $ _get ["type"]; // to display the type of news
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); // Return a one-dimensional array, the subscript is a template variable name
$ Smarty-> Display ($ ROW);
UNSET ($ row); $ conn-> close ();
?>
============================================================================================================================================================================================================= ===========
Explain the key place, in fact, there is only one place value in News.php.
1. $ conn-> getrow ($ strquery): This sentence returns a one-dimensional array, the return form is:
$ array = ("newstitle" => "xxxx", "newscontent" => "YYYYY ...")
I understand what if smarty will do if SmartY is used after using $ smarty ($ array)? It is equivalent to:
$ Smarty-> Assign ("NewStitle", "XXXX");
$ Smarty-> Assign ("NewsContent", "YYYYY ...");
Simple, it is really simple
Let's take a look at the newslist:
============================================================================================================================================================================================================= ==============
Newslist.php
============================================================================================================================================================================================================= ==============
PHP
/ ***************************************************
*
* File name: newslist.php
* Job: News list display
*
* Servers: Master
* Email: teacherli@163.com
*
*************************************************** /
INCLUDE_ONCE ("./ Comm / MySmarty.class.php"); // contains Smarty's extended class file
INCLUDE_ONCE ("./ Comm / AdoDB / AdoDb.inc.inc.php"); // contains Adodb main execution file $ smarty = new mysmarty (); // Establish a smarty instance object $ smarty
$ conn = adonewconnection ("mysql"); // Initialize AdoDB
$ conn-> connect ("localhost", "root", "" ""); // Connect the database
$ Newsid = $ _get ["id"]; // Get news numbers
$ Newstype = $ _get ["type"]; // to display the type of news
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 assen newstitle from". $ tbname;
1. $ r = & $ conn-> getall ($ strquery);
2. $ Smarty-> Assign ("NewSType", $ newstype); // This sentence is the link service in the news list
3. $ SMARTY-> Assign ("Newslist", $ RS);
UNSET ($ RS);
$ conn-> close ();
$ Smarty-> Display ("newslist.tpl");
?>
============================================================================================================================================================================================================= ==============
Take it separately:
1. Getall ($ strquery): This function is a good stuff, its role is to combine all the data combinations from $ STRQUERY to be a two-dimensional array that can be identified by Smarty.
Remember: It returns a two-dimensional array instead of a recordset, you can use it directly in the program.
2. Here is to give the news header to make a link to get parameter type = xx
postscript:
Everyone has several places to pay attention to using AdoDB:
1. Initialization: Initialization does not use new because it is not an object
2. Method: Basically, each method is a name that is mixed with uppercase letters. This seems to be different from * NIX habits, and it is different from the overall style of PHP.
Note that the case is written here.
Ok, this SMARTY's series of tutorials is basically completed here. Even if the primary tutorial is to throw the jade, I hope more masters will write more experience. Everyone
Common improvement! Because the company is not allowed to open QQ, if everyone wants to communicate with me, please add my MSN: teacherli@ceua.org, welcome everyone to discuss!