SMARTY instance teaching example articles [Repost]

xiaoxiao2021-03-06  22

SMARTY instance teaching example articles [Repost]

Author: YeahTech Source: Yeah !! Networking Academy Joined: 2004-11-3

SMARTY instance teaching instance article (III, using the AdoDB connection database) Because the work is very busy, since there is no time to complete this tutorial in time, just don't have to work overtime today, take an empty! When the tutorial, I first modified some of the wrong places in the tutorial I wrote, I would like to thank Nesta2001zhang brothers, he found some mistakes in the article, otherwise it was really awkward " The wrong child is "" It's really embarrassing, I found a lot of problems after the release of my preliminary, and later I had a mistake in the file after returning, it shouldn't ...) The above tutorial: ================================================================================================================================================================================================= ============== While ($ db-> next_record () && $ i> 0) {$ array [] = array ("newsid", csubstr ($ db-> f (" inewsid "), 0, 20)," newstitle ", csubstr ($ db-> f (" vcnewstitle "), 0, 20)); $ I -;} ============ ==================================================================================================================================== ============================================================================================================================================================================================================= ====== While ($ db-> next_record () && $ i> 0) {$ array [] = array ("newsid" => $ db-> f ("inewsid"), "newstitle" => CSUBSTR ($ db-> f ("vcnewstitle"), 0, 20)); $ I -;} ========================== =========

======================== Why do you change this? Because the second method is clearer, the effect is actually performed in the first way. There is no difference in the second method, and I have been debugged, there is no problem. Well, then we will talk about Adodb today, say adoDB, I can do ADO for the Windows platform. Components, but our AdoDB is not Microsoft's database operation component, but a set of database operations libraries written by PHP language, let's take a look at what it does. 1. Take standard SQL The database execution code written by the statement does not have to change the source when performing database transplantation, that is, it can support multiple databases, including Access. 2. Provides syntax features similar to Microsoft AdoDB. This is a person from ASP to PHP It is a big gospel, and its many operations are similar to the AdoDB in Windows. 3. You can generate the two-dimensional array required for the Smarty cycle, which will simplify Smarty development. This is to give you a demonstration. 4. Support the database Cache queries, 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 huge, it is 107K, so if you consider the efficiency, you must think about it. But to be honest, its Function is still very powerful, there are many very practical features, using it these features, can be very convenient to implement the features we want. So everyone does not prevent it when there is no special requirement, 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? Decompress the lower-loaded compressed file, pay attention: Everyone downloads the format for adoDb.tar.gz, which is the compressed format of Linux, you can use WinRAR to decompress it, after decompression The directory is copied to the AdoDB directory of the specified directory, which is copied to / comm / adoDB / in the example. Third, how to call AdoDB? Use include_once ("./comm/adodb/adodb.inc.php"); don't say it? Contains the main file of AdoDB. Fourth, how to use ADODB? 1. Permerate: AdoDB uses $ conn = adonewconnection (); this statement is initialized, and there are two ways to initialize AdoDB: The first way is: Traditional way. I temporarily called it for this name. It uses a new way to build a standard connection method 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 perform initialization, and the DSN is written as: $ dsn = "dbtype: // user: passwd @ host / dbname"; where DBTYPE represents the database Type, user name, passwd is the password, Host is the server name, dbname is the database name, like this, I use the Oracle database, the username: Oracleuser, the password is OraclePasswd, the database server is Localhost, the database is ORADB DSN writes: $ DSN = "Oracle: // OracleUserraclePasswd @ localhost / oradb"; $ conn = new adonewconnection ($ DSN); this way may be more interested from programmers coming from ASP. Both of these ways can be used, to see personal habits. 2. Related concepts: Use AdoDB has two basic classes, one is the Adoconnection class, the other is the AdoCordset class, people who have used ASP These two classes will understand its meaning, and adoConnection refers to the class of database connections, and the AdoCordSet refers to the data category returned by the AdoConnection, and the relevant information can query the AdodB class manual. 3. Basic functions: The relevant methods for the Adoconnection class are: 1.Connect: Database connection method, we introduced it on the top. For MySQL, there is PConnect, just as used in the PHP language. 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 don't remember to write a list of news lists that need to be displayed on the page when I write about the input list in the previous tutorial. 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 to generate $ array [0] = array ("newsid" => 1, "newstitle" => "News here"); $ array [1] = array ("newsid = > 2, "newstitle" => "Article 2 of the news"); ... this form, but if we don't need to control the title, we have a blessing in AdoDB, we can write: == ============================================================================================================================================================================================================= ==========

==================== $ strquery = "select inews, vcnewstitle from tb_news_ch"; $ array = & $ conn-> getAll ($ strquery); // pay attention to this Statements $ smarty-> assign ("news_ch", $ array); unset ($ array); ============================ ============================================================================================================================================================================================================= ==== Of course, the $ 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 why some people will say that 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 that it is a limited query statement. It has a simple example with the LIMIT in the mysql statement. A simple example: $ r = $ conn-> selectlimit ("Select inewsid, vcnewstitle from tb_news_ch", 5, 1); Is it clear? Saved in $ RS is 5 records from the first record in the database. We know, in the Oracle database does not support using limit in the SQL statement, but if we use 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): Return to the value of the field. 2. RecordCount (): The number containing the record. Record the total number of records to determine the data set. 3. GetMenu ($ name, [$ default_str = '], [$ bulk1stItem = true], [$ multiple_select = false], [$ size = 0], [$ moreattr =' " ]) Very good 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 pointed out whether the first item is empty, $ multiple_select points to whether it is a multi-selection box, and we get this string, you can use $ smarty- > ("Templatevar", "getmenustr") to enter a drop-down list (or more box) at the TemplateVar "4.MoveNext (): to see a code: ========== =============================================== $ = = = & $ conn-> Exceute ($ SQL); if ($ r) {While ($ RS-> EOF) {$ Array [] = array ("newsid" => $ @ >-> fields [inewsid "]," Newstitle "=> csubstr ($ RS-> Fields [" vcnewstitle "]), 0, 20); $ r r =xt ();}} ================= ======================================== understand? It is very similar to MS AdoDB That one! 5. MoveFirst (), movest (), Move ($ to): The same, see the function name everyone can know what it means. 6. fetchrow (): Return one line, see code: = =================================================================================================================================================================================

============== $ = & $ conn-> exceute ($ sql); if ($ r) {while ($ row = $ r-> fetchrow ()) {$ array [] = array ("newsid" => $ row ["inewsid"], "newstitle" => csubstr ($ row ["vcnewstitle"]), 0, 20);}} ========= ================================================ it implements it The same function 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 is used in an example index.php. 8. Close (): With mySQL_Free_Result ($ RS); Clear 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 cache Inquiry, with query, etc., you can view the manual yourself. Below us, let's start learning our procedures, the same, the same web program, I will reorganize it, and in order to improve the efficiency to re-encapsulate SMARTY, MySmarty.class.php is a packaged class, which inherits from smarty, so only new class mysmarty in all program files later, first check the directory structure: web (site root directory) | | ---- Comm (Smarty Related Document Directory) | | | | ---- Smarty | | ---- AdoDB (AdoDB Original Directory) | | ----- mysmarty.class.php (Extended Smarty file) | | ----- Csubstr.inc (intercept Chinese characters) | | ---- cache (smarty cache directory, * NIX to ensure read / write permissions) | | ---- Templates | | | | ---- Header.tpl (Page Tablet Template File) | | ---- Index.tpl (Site Home Template File) | | ---- Foot.tpl (Page footer template file) | | ---- news.tpl (news page template file) | | | ---- templates_c (Sewage Directory after compiling, * NIX) | | --- CSS (Site CSS Directory) | | ---- Image (Site Picture Directory) | | ----

Media (Site Flash Animation) | | ---- IndexBak.htm (Home Original Render) | | ---- NewsBak, HTM (News Page Original Render) | | ---- Index.php (Smarty Home program files) | | ---- news.php (Smarty News Display File) | | ---- NewsList.php (Show News List) | | ---- routine Description .txt (this document) relative The first two tutorials, there is a reorganization of the Comm-directory, and other file structures have not changed. The whole site is relatively two tutorials, and the changed place has only a Comm-directory and index.php and news.php, while increasing News list, you can click "Domestic News", International News "," Entertainment News "to view the respective news lists in Index.php execution, let's take a look at Index.php: ==== ============================================================================================================================================================================================================= INDEX.PHP =============================================================================================================================================================================================== ======= Connect ("Localhost", "root", "" "," News "); // Connect the database // Here you will handle the domestic news section 3. $ strquery =" SELECT INEWSID AS NEWSID, VCNEWSTID AS NEWSTILEWSID DESC "; 4. $ c = &

$ conn-> execute ($ STRQUERY); 5. $ Smarty-> Assign ("news_ch", $ rs-> getArray (news_num)); 6. Unset ($ r); // Treat the International News section $ 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 ($ r); // will process the entertainment news section $ strquery = "SELECT INEWSID AS NEWSID, VCNEWSTILE AS NEWSID, VCNEWS_MU ORDER BY INEWSID DESC"; $ RS = & $ conn-> execute ($ strquery); $ Smarty-> Assign ("news_mu", $ r-> getArray (news_num)); unset ($ r); 7. $ conn-> close (); // Compile and display the index.tpl on ./Templates under the INDEX.TPL template $ smarty-> display ("index.tpl");?> =================================== ===========================================, I am in key places The scalar, here to explain their meaning: 1. Create a connection object $ conn, everyone should pay attention to it is that its initial appearance is in the form of $ conn = new adonewconnection ($ dbtype), that is Said, 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, user name is "" 3. One query statement, note, here you want to use the query field to re-identify, named the name of the template variable you set in the template. 4. Use EXECUTE To perform this query, the result is returned to a Recordset dataset 5. Here is a method: $ r-> getArray ($ NUM) This is introduced, it is to return to $ NUM line from the data set of $ r, the result is one Can be identified by Smarty. This is automatically built for us, and in our previous example, it is used to build such an array using a loop. 6. I don't have to see this sentence. Say it? 7. Turn off the relevant resources in memory. You can look at it. The whole program does not appear anything statement, the overall structure of the program is very clear, this is why ADODB

Smarty is the reasons for the gold combination. But the words also come back, simple and simple questions, I don't know if you think about it, here is not controlled, that is, if a piece of news title is exceeded The scope of the display, it is automatically folded to the next line, then the entire layout will mess up, and everyone says that you have used it to use it. Of course, you can also use the previous section. Use a loop statement to reconstruct this two-dimensional array, so that it meets your use, how to do yourself, refer to PHPLIB practices, I introduced the next section ... Let's take a look at the news page === ============================================================================================================================================================================================================= ======== news.php ============================================================================================================================================================================================ ======================= Connect ("localhost", "root", "" "); // Connect database $ Newsid = $ _GET ["ID"]; // Get the news number $ newstype = $ _get ["type"]; // To display the news type Switch ($ newstype) {casse 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 to a one-dimensional array, the subscription is a template variable name $ smarty-> Display $ row; unted ($ row); $ conn-> close ();?> =============================== =============================== Describes the key to the critical place, in fact, only one local value in news.php I'm here. 1. $ conn-> getrow ($ strquery): This sentence returns a one-dimensional array, the return form is: $ array = ("newstitle =>" xxxx "," newscontent "=>" YYYY .. "I understand what if smarty will do after using $ smarty ($ array)? Yes, it is equivalent to: $ smarty-> assign (" newstitle "," xxxx "); $ smarty-> assign (" newscontent ", "YYYYY ..."); simple, it is really simple to see the news list: ============================== ===================================1slist.php ================================================================================================================================================================================================================================================ ============================================================================================================================================================================================================= ==

163.com * *************************************************** / INCLUDE_ONCE ("./ Comm / MySmarty.class.php"); // contains Smarty's extended class file include_once ("./ Comm / AdoDB / AdoDb.inc.php"); // contains Adodb main execution file $ smarty = New mysmarty (); // Established a Smarty instance object $ SMARTY $ conn = adonewconnection ("mysql"); // Initialize Adodb $ conn-> Connect ("localhost", "root", ""); / / Connect Database $ NEWSID = $ _GET ["ID"]; // Get news numbers $ newstype = $ _get ["type"]; // To display news type Switch ($ newstype) {casse 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.. $ r = & $ conn-> getAll ($ STRQUERY); 2. $ SMARTY-> Assign ("newstype", $ newstype); // This sentence is a link service in the news list 3. $ smarty-> assign (" Newslist ", $ RS); unset ($ RS); $ conn-> close (); $ smarty-> display (" newslist.tpl ");?> ============== ============================================================================================================================================================================================================= To explain: 1. Getall ($ strquery): This function is a good stuff, its role is to combine all the data to be queried by the $ STRQUERY into a two-dimensional array that can be identified by Smarty, remember: it Returns a two-dimensional array instead of a recordset, You can use them directly in the program. 2. Here is to give the news headline to make a link to get parameter type =

转载请注明原文地址:https://www.9cbs.com/read-39977.html

New Post(0)