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 (said it is really embarrassing, after my first draft is released, I found it in a big pile, and then there was a mistake in the document after returning to revisions. It shouldn't be ...) Several tutorials: ============================================ ============= while ($ db-> next_record () && $ i> 0) {$ array [] = array ("newsid", csubstr ($ db-> f ("inewsid "), 0, 20), 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 is this changed? Because the second method is clearer, it is more clear, and the effect of the first method is nothing to do with the second method. Difference, and those programs I have been debugged, there is no problem. Ok, then we will talk about Adodb today, say adoDB, may have an ADO component of the Windows platform, but we here AdoDB is not Microsoft's database operation component, but a set of database operation class libraries written by PHP language first, let's take a look at what it is. 1. Database performed by standard SQL statement The code does not need to change the source when performing database transplantation, that is, it can support multiple databases, including Access.2. Provide similar syntax features similar to Microsoft AdoDB. This is a great gospel for people from ASP to PHP. Many of its operations are similar to the ADODB in Windows. 3. You can generate the two-dimensional array required for the Smarty loop, which simplifies Smarty development. This is the wait for me to give you a demonstration. 4. Support the database's cache query, the biggest possible 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. Perform initialization: AdoDB adopts $ conn = adonewconnection (); this statement is initialized, and there are two ways to initialize AdoDB: The first mode 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: // Oracleuser: OraclePasswd @ localhost / oradb"; $ conn = new adonewconnection ($ DSN); this way may be more interested in programmers coming from ASP. Both of these ways, to see personal habits to choose .2. Related concept: 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); // Note this statement $ Smarty-> Assign; 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 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 included in the record. This 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" of the template 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 (), Movese (), Move ($ to): The same, see the function name everyone can know what it means. 6. Fetchrow (): Return one line, see code: = =================================================
========= $ = & $ conn-> exceute ($ s); if ($ r) {while ($ row = $ r-> fetchrow ()) {$ array [] = array ( "Newsid" => $ row ["inewsid"], "newstitle" => CSUBSTR ($ row ["vcnewstitle"]), 0, 20);}} ============== ============================================ it achieved 4 Function, 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 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 is called in all program files, first come to see 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 guaranteed reading and writing 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 compilation, * NIX) || --- CSS (Site CSS Directory) || ---- Image (Site Picture Directory) || ----
Media (Site Flash Animation) || ---- IndexBak.htm (Home Original Render Map) || ---- 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) is 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 =============================================================================================================================================================================================== ======= PHP / ************************************************** ******** file name: index.php * effect: an example routine ** author: big Brother * Email: teacherli@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 include_once (" ./ CommM /csubstr.inc "); // contains Chinese interception class define (" news_num ", 5); // Defines the list of news lists $ smarty = new mysmarty (); // Establish a smarty instance object $ smarty1. $ conn = adonewconnection ("mysql"); // Initialize AdoDB2. $ conn-> connect ("localhost", "root", "" "); // Connect the database // here will process the domestic news section 3. $ strQuery = "SELECT INEWSID AS NEWSID, VCNEWSTIL AS NEWSID DESC"; 4. $ = & $ conn-> execute ($ strquery); 5. $ Smarty-> assign ("news_ch", $ r-> getArray (News_num); 6. UNSET ($ r); // Treated international news part $ strquery = "SELECT INEWSID AS NEWSID, VCNEWSTILE AS NEWSID, VCNEWSTITLE AS NEWSID, VCNEWS_IN ORDER BY INEWSID DESC"; $ RS = & $ conn-> execute ( $ STRQUERY); $ SMARTY-> Assign ("news_in", $ r-> getArray (news_num)); unset ($ r); // will address entertainment news parts $ strquery = "Select inewsid as newsid, vcnewstitle as newstitle From TB_News_Mu Order by inewsid desc "; $ = & $ conn-> execute ($ STRQUERY); $ smarty-> assign "News_MU", $ r gar (news_num)); unset ($ r); 7. $ Conn-> close (); // Compile and display the index.tpl on ./TPL Template $ 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 $ conn = new adonnection ($ dbtype) In this form, that is, AdonEnnection 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 it? Open a new database, the host is: localhost, the username root, the password is "" 3. A query statement, note, here you want to use the query field to re-identify, the name is set in the template The name of the template variable. 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 from $ r The result is returned to the $ NUM line, the result is a two-dimensional data that can be identified by Smarty. Such ADODB automatically builds such a structure for us, and in our previous examples, use a loop to build such an array I don't have to say it? 7. Close the relevant resources in memory. You can check out what the While statement appears in the entire program, 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 displayed range, it is automatically folded to the next line, then the entire layout will mess up, and everyone says that the situation has been appropriate to use it :) Of course, you can also use it in the previous section. In that, use a circular statement to reconstruct this two-dimensional array, so that it meets your use, how to do yourself, refer to the practice in phplib, I introduced the next section ... Let's take a look at the news page = ============================================================================================================================================================================================================= ========== news.php ======================================== ===========================? ****************************** ************************* file name: news.php * role: News display program ** author: big Brother * Email: teacherli @ 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 ); // Establish a Smarty instance object $ smarty $ conn = adonewconnection ("mysql"); // Initialize Adodb $ Conn-> Connect ("LocalHost", "Root", ""); // Connect the database $ Newsid = $ _GET ["ID"]; // Get the news number $ newstype = $ _get ["type"]; // To display the news type 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, subscript is a template variable name $ smarty-> display ($ row); unset ($ row); $ conn-> close ();? > ================================================================================================================================================================= ============ Description Take the key place, in fact, there is only one place value in News.php .1. $ Conn-> getrow ($ strquery): This sentence returns one One-dimensional array, the return form is: $ array = ("newstitle" => "xxxx", "newscontent" => "YYYYY ...") understand what if SmartY will do after using $ smarty? It is equivalent to: $ smarty-> assign ("newstitle", "xxxx"); $ smarty-> as Sign ("NewsContent", "YYYYY ..."); simple, it is really simple to look at the news list: ======================= ==================
======================= newslist.php ========================= ================================================= php / ****** ***************************************** File name: newslist.php * role: News list display program ** author: big Brother * Email: teacherli@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 ); // Establish a Smarty instance object $ smarty $ conn = adonewconnection ("mysql"); // Initialize Adodb $ Conn-> Connect ("LocalHost", "Root", ""); // Connect the database $ Newsid = $ _GET ["ID"]; // Get the news number $ newstype = $ _GET ["type"]; // To display the 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. $ = & $ 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");?> ==================== =============================================== respectively Taken: 1. getAll ($ strquery): This function is a good stuff, its role is to combine all the data invested by $ STRQUERY to be a two-dimensional array that can be identified by Smarty, remember: it returns A two-dimensional array rather than 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 TY PE = XX after the post: Everyone has several places when using AdoDB: 1. Initialization: Initialization is not using new because it is not an object 2. Method: Basically, every method is uppercase letters The name of the mixed mix, this seems to be different from the habits of * NIX, and it is different from the overall style of PHP, so pay attention to the case here. Ok, this Smarty's series of tutorials will basically have completed it. Even if the primary tutorial is a throwing brick, I hope more masters will write more experience, and everyone will improve! Because the company is not allowed to open QQ, if you want to communicate with me, please add My MSN: Teacherli@ceua.org, welcome everyone to discuss! ====
============== The following is the relevant directory file: Web.rar This file has been downloaded 46 times.
Happybot automatically picks from Joy Village Essence Post, check the original post to get the full content