Smarty Example Teaching example (third, using ADODB connection database)
The first two months because of the cause of the work has been very busy, so did not complete the tutorial in time, just today Saturday without overtime, smoke a blank to complete it! At the beginning of the new tutorial, I
First of all, I wrote in the previous tutorial some of the wrong place to change, here to thank the Nesta2001zhang brothers, is he found some of the article errors, otherwise really be someone
Scold "fraught" (say really ashamed, my first draft after the release found in a lot of problems, and then some time after the re-modification of the file unexpectedly also appeared errors, really should not
The ...)
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--;
}
=========================================================
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 did you change it? Because the second method is clearer, the first way is actually the same as the second method, and I've debugged those programs,
There is no problem.
Well, let's talk about ADODB today. When it comes to ADODB, it's possible that ASP knows the ADO components of the Windows platform, but our ADODB here is not the Microsoft database.
As a component, instead of a database Operation class library written in PHP, let's look at what the upside is.
1. Database execution code written in standard SQL statements does not have to change the source program when the database is migrated, which means it can support multiple databases, including access.
2. Provides syntax features similar to Microsoft ADODB. This is a great boon for people who switch from ASP to PHP, and many of the operations are similar to the ADODB in Windows.
3. You can generate a two-dimensional array that is required for the Smarty Loop, which simplifies smarty development. This is what I'm going to show you.
4. Support the database Cache query, the maximum possible increase the speed of querying the database.
5. Other useful functions.
Although there are many advantages, but because this kind of library is very large, light its main execution class is 107K, so if you consider the implementation of efficiency, you need to think carefully. But honestly, it's
function is still very powerful, there are a lot of very useful features, using its features, can be very convenient to achieve the functions we want. So for those bosses who don't have a special request, they don't
Use it for protection.
First, how to get ADODB? What is its operating environment?
From Http://sourceforge.net/project/show ... 簆 hp4.0.5 above.
Second, how to install ADODB?
Unzip the download back to the compressed file, note: Everyone download back the format for ADODB.tar.gz, this is the compression format of Linux, under Windows Everyone can use WinRAR to it into
Extract the directory into the ADODB directory of the specified directory, as I copied it to/comm/adodb/in the example.
Third, how to call ADODB?
Use Include_once ("./comm/adodb/adodb.inc.php"); that's not the line, is it? The primary file that contains the ADODB.
Iv. How to use ADODB?
1. Initialize:
ADODB uses $conn = Adonewconnection (), such statements are initialized, and there are two ways to initialize ADODB:
The first way is: the traditional way. I call it the name for the time being. It uses a way to create a new connection much like the standard connection in PHP:
$conn = new Adonewconnection ($dbDriver);
$conn->connect ($host, $user, $passwd, $db);
Simple, huh? If you have used the DB class in Phplib, you should be familiar with it.
The second way: the use of DSN mode, so that the database connection statement written as a statement to initialize, DSN has the following: $dsn =
"Dbtype://user:passwd@host/dbname"; Where DbType represents the database type, user represents the username, passwd is the password, host is the server name, dbname is the database name
, like this I use Oracle database, user name: Oracleuser, password is ORACLEPASSWD, database server is localhost, database for oradb DSN writes:
$DSN = "ORACLE://ORACLEUSERRACLEPASSWD@LOCALHOST/ORADB";
$conn = new Adonewconnection ($DSN);
Programmers who are likely to switch from ASP to this approach will be more interested.
Both of these methods can be used, depends on personal habits to choose.
2. Related concepts:
There are two basic classes using ADODB, one is the ADOConnection class, the other is the Adorecordset class, and the person who used the ASP sees that the two classes will understand its meaning,
ADOConnection refers to the class of database connection, and Adorecordset refers to the data set class returned by ADOConnection execution query statement, the relevant information can be queried ADODB
The Manual of the class.
3. Basic functions:
The relevant methods for the ADOConnection class are:
1.Connect: Database connection method, above we introduced. For MySQL and Pconnect, as in the PHP language
2.Execute ($sql): Executes a query statement result returns a Adorecordset class.
3.GetOne ($sql): Returns the first field of the first row
4.GetAll ($sql): Returns all data. This function is very useful, remember I wrote in the previous tutorial about the input of the news list will need to be displayed on the page
The news list is made into a two-dimensional array? This is the statement:
=====================================================================================
while ($db->next_record ())
{
$array [] = Array ("NewsID" = = $db->f ("Inewsid"),
"Newstitle" = Csubstr ($db->f ("Vcnewstitle"), 0, 20));
}
=====================================================================================
What does this line mean? is to generate the news sample table that will be displayed
$array [0] = Array ("NewsID" =>1, "newstitle" = "The first article of the news here");
$array [1] = Array ("NewsID" =>2, "newstitle" = "The second article of the news here");
...
Such a form, but if we do not need to control the title, in the ADODB we are blessed, we can write:
==================================================================================
$strQuery = "Select INews, Vcnewstitle from Tb_news_ch";
$array = & $conn->getall ($strQuery);//Note this statement
$smarty->assign ("News_ch", $array);
Unset ($array);
==================================================================================
Of course, the $conn here should be initialized, I do not know you see it? Originally I want to manually create two-dimensional data here directly using GetAll on the line!!! This is also for
What someone would say Adodb+smarty is one of the reasons for the invincible combination ...
4.SelectLimit ($sql, $numrows =-1, $offset =-1, $inputarrr =false): Returns a data set, it is not difficult to see from the statement that it is a limited query language
Sentence, which is similar to the limit in the MySQL statement, comes in a simple example:
$rs = $conn->selectlimit ("Select Inewsid, Vcnewstitle from Tb_news_ch", 5, 1);
Did you see that? The $rs saves 5 records in the database starting with the first record. We know that the use of limit in SQL statements is not supported in Oracle databases, but if we make
With ADODB words, that problem is easier to solve more!
5.Close (): Close the database, although PHP will automatically close at the end of the page, but in order to complete the program you still have to close the database at the end of the page.
As for the result of Adorecordset.adorecordset returning for $conn->execute ($SQL), its basic functions are as follows:
1. Fields ($colname): Returns the value of the field.
2. RecordCount (): The number of records contained. This record determines the total number of records for the dataset.
3. GetMenu ($name, [$default _str= "], [$blank 1stitem=true], [$multiple _select=false], [$size =0], [$moreAttr = ']) very good
function, which can be used to return a name= $name drop-down menu (or a multi-marquee)!!! Of course, it's an HTML string, which is an exciting good thing, $name refers to
Option's Name property, $default _str is the default selected string, $blank 1stItem indicates whether the first item is empty, $multiple _select indicates whether it is a multi box, and we get this
String, you can use $smarty-> ("Templatevar", "Getmenustr") to enter a drop-down list (or multiple boxes) at the "Templatevar" of the template.
4. MoveNext (): Take a look at the 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? It's like the one in Ms ADODB!
5. MoveFirst (), MoveLast (), Move ($to): Same, look at the function name everyone can know what it means.
6. Fetchrow (): Return a line, look at the code:
=========================================================
$rs = & $conn->exceute ($sql);
if ($RS)
{
while ($row = $rs->fetchrow ())
{
$array [] = Array ("NewsID" = = $row ["Inewsid"],
"Newstitle" = Csubstr ($row ["Vcnewstitle"]), 0, 20);
}
}
=========================================================
It achieves the same functionality as 4, but it looks more like PHP's habit, while 4 of the habit looks more of a MS ADODB approach.
7.GetArray ($num): Returns the $num row data in the dataset and combines it into a two-dimensional array. This method we use in the example index.php.
8. Close (): Same as Mysql_free_result ($RS), clear content consumption.
Well, the preliminary function is introduced here, enough for our use! In fact, ADODB has a lot of practical techniques, including formatting datetime, formatted query statements, output tables, more advanced
Click on the cache query, with the reference query, etc., you can view the manual.
Here we start to learn our program, as well as the Web application, I comm the directory of the catalog, and in order to improve the efficiency of smarty re-encapsulation
, mySmarty.class.php is the encapsulated class, which inherits from Smarty, so only new class Mysmarty will be called in all future program files, first look at the directory structure:
+web (site root directory)
|----+comm (smarty Related documents directory)
| |----+smarty (smarty original file directory)
| |----+adodb (ADODB original catalogue)
| |-----mySmarty.class.php (Extended Smarty file)
| |-----csubstr.inc (intercept Chinese characters)
|----+cache (smarty cache directory, *nix guaranteed read and Write permissions)
|----+templates (site template file storage directory)
| |----HEADER.TPL (page header template file)
| |----INDEX.TPL (site homepage template file)
| |----FOOT.TPL (page footer template file)
| |----NEWS.TPL (Press page template file)
|
|----+templates_c (template file after compiling directory, *nix guaranteed read and Write permissions)
|----+CSS (site CSS file directory)
|----+image (site image catalog)
|----+media (SITE Flash animation storage directory)
|----indexbak.htm (home original)
|----newsbak,htm (News page original)
|----index.php (smarty Home program file)
|----news.php (SMARTY news show file)
|----newslist.php (SHOW news list)
|----Routines description. txt (this document)
Compared to the first two tutorials, there is the Comm directory has been re-organized, the other file structure has not changed, the entire site compared to the two tutorials, the change is only the Comm directory and
index.php and news.php, at the same time added news list, you can click on the index.php after the execution of the page "domestic News", "International News", "Entertainment news" to view their respective
News list, let's take a look at index.php:
======================================================
index.php
======================================================
/*********************************************
*
* File name: index.php
* Function: Show instance Program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file that contains Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files
Include_once ("./comm/csubstr.inc"); Includes Chinese intercept class
Define ("News_num", 5); Define the number of news list displays
$smarty = new Mysmarty (); Establish the Smarty instance object $smarty
1. $conn = adonewconnection ("MySQL"); Initialize ADODB
2. $conn->connect ("localhost", "root", "" "," News "); Connecting to a 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);
Handling the international news section here
$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 located under./templates
$smarty->display ("Index.tpl");
?>
=============================================================================
In the same way, I add a few keys to the key places, and here's what they mean:
1. Establish a Connection object $conn, it is important to note here that its initial is not in the form of $conn = new Adonewconnection ($dbType), which means
, Adonewconnection is not a class and you cannot initialize it with new. Look at its source code and you'll see that it's just a function.
2. Does this have to be said? Open a news database, host: localhost, username is root, password is ""
3. A query statement, note that the query field here is to use the AS keyword to re-identify the name of the template variable you set in the template name.
4. Execute this query using EXECUTE to return a recordset data set
5. Here is a method: $rs->getarray ($num) This is introduced above, it is to return from $rs this dataset $num rows, the result is a smarty can be recognized by the two-dimensional number
The ADODB automatically constructs such a structure for us, and in our previous example, we use a loop to construct such an array.
6. I don't have to say anything about this sentence?
7. Close the related resources in memory.
As you can see, there is no more of the while statement in the whole program, and the overall structure of the program is very clear, which is why Adodb+smarty is the gold combination. But the words
Said back, simple has a simple question, I do not know that you have thought about it, there is no control over the length of the displayed news title, that is, if a news title is longer than the length of a line display
Circumference, it is automatically folded to the next line, then the entire layout will be chaotic, said everyone has their own situation to decide whether to use it. Of course, you can also use a mediation like the previous section
Shaoxing, using a looping statement to reconstruct the two-dimensional array, so that it conforms to your use, how do you think about it, refer to the practice in phplib, I introduced the last section ...
Let's take a look at the news page.
=============================================================
news.php
=============================================================
/*********************************************
*
* File name: news.php
* Role: News display program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file that contains Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files
$smarty = new Mysmarty (); Establish the Smarty instance object $smarty
$conn = adonewconnection ("MySQL"); Initialize ADODB
$conn->connect ("localhost", "root", "" "," News "); Connecting to a database
$NewsID = $_get["id"]; Get the news number
$NewsType = $_get["type"]; The type of news to display
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, labeled as template variable name
$smarty->display ($row);
Unset ($row);
$conn->close ();
?>
=============================================================
Explain the key point, in fact, in the news.php there is only one place to explain the value.
1. $conn->getrow ($strQuery): This sentence returns a one-dimensional array, returned in the form:
$array = ("Newstitle" = "xxxx", "newscontent" = "yyyyy ...")
Do you understand what smarty will do if you use $smarty ($array)? Yes, that's the equivalent of:
$smarty->assign ("Newstitle", "xxxx");
$smarty->assign ("Newscontent", "yyyyy ...");
Simple, it's really simple.
Let's take a look at the news list below:
================================================================
newslist.php
================================================================
/*********************************************
*
* File name: newslist.php
* Role: News list Display program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file that contains Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files
$smarty = new Mysmarty (); Establish the Smarty instance object $smarty
$conn = adonewconnection ("MySQL"); Initialize ADODB
$conn->connect ("localhost", "root", "" "," News "); Connecting to a database
$NewsID = $_get["id"]; Get the news number
$NewsType = $_get["type"]; The type of news to display
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 is a link service in a news list
3. $smarty->assign ("Newslist", $rs);
Unset ($RS);
$conn->close ();
$smarty->display ("Newslist.tpl");
?>
================================================================
Separately to illustrate:
1. GetAll ($strQuery): This function is a good thing, its role is to $strquery all the data queried into a smarty can be recognized by the two-dimensional array,
Remember: It returns a two-dimensional array instead of a recordset, where you can use the program directly at 3.
2. This is to make a link to the news headlines to get the parameter type=xx to do
Postscript:
There are several places to note when you use ADODB:
1. Initialization: The method of initialization is not using new because it is not an object
2. Method: Basically each method starts with uppercase and lowercase mixed names, which seems to be somewhat different from *nix's habits, but also different from the overall style of PHP, so
Pay attention to the capitalization problem here.
Well, this smarty series of tutorials to the basic has been completed, I have a few of these introductory tutorials, I hope more experts will write more experience, we
Joint Improvement! Because the company does not allow QQ, if you want to communicate with me, please add my msn:teacherli@ceua.org, welcome everyone to discuss together!
(Source: Viphot)
http://www.bkjia.com/PHPjc/314055.html www.bkjia.com true http://www.bkjia.com/PHPjc/314055.html techarticle Smarty Example Teaching example (third, using ADODB connection database) Two months ago because of the reasons for the work has been very busy, so did not complete this tutorial in time, just today Saturday without overtime ...