Smarty Example Teaching Example

Source: Internet
Author: User
Tags empty execution functions header connect sql mysql oracle database
Smarty Example Teaching examples (III., using ADODB connection database)

The first two months because of the reasons for the work has been very busy, so did not complete this tutorial in time, just today in Saturday do not have to work overtime, draw an empty finish it! At the beginning of a new tutorial, I

First of all I wrote the tutorial in the wrong place to change over, here to thank the Nesta2001zhang brothers, he found the article in some of the mistakes, or really someone else

Scold "fraught" (say is really ashamed, after my first draft was released after found in a lot of problems, then some time after the change of the document also appeared in the wrong, 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 read:
=========================================================
while ($db->next_record () && $i > 0)
{
$array [] = Array ("NewsID" => $db->f ("Inewsid"),
"Newstitle" => csubstr ($db->f ("Vcnewstitle"), 0, 20));

$i--;
}
=========================================================
Why do you do it this way? Because the second method is clearer, the effect of the first approach is no different from the second, and I've debugged all the programs,

There is no problem.
Well, let's talk about ADODB today. Speaking of ADODB, may have done ASP all know the Windows platform ADO components, but our ADODB here is not the Microsoft database

As a component, but written by the PHP language of a set of database Operations class library, let us first look at what it has the advantages of the bottom.
1. Database execution code written in a standard SQL statement does not change the source program when performing a database migration, which means it can support multiple databases, including access.
2. Provides syntax functions similar to Microsoft ADODB. This is a great boon for people who switch from ASP to PHP, and many of its operations are similar to the ADODB in Windows.
3. You can generate a two-dimensional array of smarty loops, which simplifies smarty development. This is what I'm going to show you.
4. Support the database Cache query, the most likely to improve the speed of querying the database.
5. Other practical functions.
Although the advantages are many, but because the class library is very large, light its main executive class on the 107K, so if you consider the implementation of the efficiency of the need to seriously think about it. But honestly, it's

The function is still very powerful, there are a lot of very useful functions, use it's these functions, can be very convenient to achieve the function we want. So for those bosses who don't have special requirements,

Use it for protection

First, how to get ADODB? What is its operating environment?
From the http://sourceforge.net/project/show ... 簆 hp4.0.5 above.
Second, how to install ADODB?
Decompression download back to the compressed file, note: Everyone downloaded back to the format of ADODB.tar.gz, which is the compressed Linux format, in Windows you can use WinRAR to its

Row decompression, after the decompression is completed, copy the directory to the ADODB directory of the specified directory, as I copied it into the/comm/adodb/in the example.
Third, how to invoke ADODB?
Use Include_once ("./comm/adodb/adodb.inc.php"); is that a good line? Contains the ADODB Master file.
Iv. How to use ADODB?
1. To 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 build a new connection much like the standard connection in PHP:
$conn = new Adonewconnection ($dbDriver);
$conn->connect ($host, $user, $passwd, $db);
Easy, huh? If you have used a DB class in Phplib, you should be familiar with it.

The second way: the use of DSN, this is the database of the connection statement to write a statement to initialize, DSN is written as: $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, username: oracleuser, password is ORACLEPASSWD, database server is localhost, database is oradb DSN write this:
$DSN = "ORACLE://ORACLEUSERRACLEPASSWD@LOCALHOST/ORADB";
$conn = new Adonewconnection ($DSN);
This approach may be more interesting to programmers who switch from ASP.

Both of these methods can be used, it depends on the personal habits to choose.

2. Related concepts:
Using ADODB there are two basic classes, one is the ADOConnection class, the other is the Adorecordset class, and people who use ASP see these two classes to understand what it means.

ADOConnection refers to the database connection class, and Adorecordset refers to the ADOConnection execution query returns the DataSet class, the relevant information can be queried ADODB

The manual for the class.

3. Basic functions:

Related methods for the ADOConnection class are:
1.Connect: Database connection method, which we have described above. For MySQL and Pconnect, as in the PHP language
2.Execute ($sql): Execute query statement result returns a Adorecordset class.
3.GetOne ($sql): Returns the first field in the first row
4.GetAll ($sql): Returns all data. This function is of great use, remember what I did when I wrote about the news list in my previous tutorial, I want to show you what I need to see on the page

A two-dimensional array of news listings? 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 the list of news cases that will be displayed.
$array [0] = Array ("NewsID" =>1, "Newstitle" => "the first article of the press here");
$array [1] = Array ("NewsID" =>2, "Newstitle" => "the second article of 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 if we see it? The two-dimensional data I'm going to create manually here is directly using GetAll.!!! This is also for

What would anyone say Adodb+smarty is one of the reasons for the invincible combination ...
4.SelectLimit ($sql, $numrows =-1, $offset =-1, $inputarrr =false): Returns a DataSet, it is not difficult to see from the statement that it is a limited query language

Sentence, and the limit in the MySQL statement has the same effect, to a simple example:
$rs = $conn->selectlimit ("Select Inewsid, Vcnewstitle from Tb_news_ch", 5, 1);
Do you understand me? The $RS holds 5 records in the database starting with the first record. We know that the Oracle database does not support the use of limit in SQL statements, but if we make

With ADODB words, then this problem is easy to solve a lot of!
5.Close (): Close the database, although the end of the page, PHP will automatically shut down, but for the integrity of the program we still want to end the page in the closing of the database.

As for the results returned by Adorecordset.adorecordset 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 included. This record determines the total number of records in the dataset.
3. GetMenu ($name, [$default _str= '], [$blank 1stitem=true], [$multiple _select=false], [$size =0], [$moreAttr = ']] very good one

function that you can use to return a name= $name drop-down menu (or multiple marquee)!!! Of course, it's an HTML string, which is an exciting good thing, $name refers to the

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 multiple-selection box, and we get this

String, you can use $smarty-> ("Templatevar", "Getmenustr") to enter a drop-down list (or multiple first 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 suit in Ms ADODB.
5. MoveFirst (), MoveLast (), Move ($to): The same, look at the function name everyone can know what it means.
6. Fetchrow (): Return one line to see the code:
=========================================================
$rs = & $conn->exceute ($sql);
if ($RS)
{
while ($row = $rs->fetchrow ())
{
$array [] = Array ("NewsID" => $row ["Inewsid"],
"Newstitle" => csubstr ($row ["Vcnewstitle"]), 0, 20);
}
}
=========================================================
It implements the same functionality as 4, but it looks more like a PHP habit, and 4 of the habit looks more likely to be a MS ADODB approach.

7.GetArray ($num): Returns the $num row data in a dataset and combines it into a two-dimensional array. This method we use in the example index.php.

8. Close (): With Mysql_free_result ($RS);

Well, the preliminary function is introduced here, enough for us to use! In fact, ADODB also has a lot of practical techniques, including formatting date time, formatting query statements, outputting tables, and more advanced

Point of the cache query, with the reference query and so on, you can view the manual.

Let's start with our program, which is also the Web program, where I've comm the directory, and I've encapsulated the smarty to improve efficiency.

, mySmarty.class.php is the encapsulated class, which inherits from Smarty, so that only new class Mysmarty will be invoked in all subsequent program files, first look at the directory structure:
+web (site root directory)
|
|----+comm (smarty Related documents directory)
| |
| | |----+smarty (smarty original file directory)
| |----+ADODB (ADODB source directory)
| | |-----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 template file)
| | |----FOOT.TPL (page footer template file)
| | |----NEWS.TPL (News page template file)
|
|
|----+templates_c (the template file is compiled and stored in the directory, *nix guaranteed read and Write permissions)
|
|----+CSS (site CSS file directory)
|
|----+image (site picture catalogue)
|
|----+media (SITE Flash animation storage directory)
|
|----indexbak.htm (Original effect Chart of home page)
|
|----newsbak,htm (News page original effect chart)
|
|----index.php (smarty Homepage program file)
|
|----news.php (SMARTY News display file)
|
|----newslist.php (SHOW news list)
|
|----Routines description. txt (this document)

Compared to the first two tutorials, there will be a Comm directory, the other file structure has not changed, the entire site compared to the previous two tutorials, the change in the place only Comm directory and

Index.php and news.php, while adding a news list, you can click on the index.php after the implementation of the page "domestic News", "International News", "Entertainment news" to view their respective

News listings, let's take a look at index.php:

======================================================
index.php
======================================================
<?php
/*********************************************
*
* FileName: index.php
* Role: Show Instance Program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file containing Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files
Include_once ("./comm/csubstr.inc"); Include Chinese interception class

Define ("News_num", 5); Define the number of news list displays

$smarty = new Mysmarty (); Establish a 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);


Dealing with 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 that is located under./templates
$smarty->display ("Index.tpl");
?>
=============================================================================
Again, I add a number to the key points, and here's how they mean:

1. To establish a Connection object $conn, what you should note here is that its initial appearance is not in the form of $conn = new Adonewconnection ($dbType), that is to say

, Adonewconnection is not a class, and you can't initialize it with new. Look at its source code you'll see, it's just a function.

2. What about this? Open a news database, the host is: localhost, user name is root, password is ""

3. A query statement, note that here to the query's fields using the AS keyword to be identified, the name of the template you set in the template variable name.

4. Execute this query using execute, and the result returns a recordset dataset

5. Here's a way: $rs->getarray ($num), which is described above, is to return $num rows from the $rs dataset, resulting in a two-dimensional number that can be smarty recognized

So ADODB automatically built this structure for us, and in our previous example, we used a loop to build such an array.

6. I don't have to say that, can I?

7. Close the related resources in memory.

You can see, the entire program has not appeared any while statement, the overall structure of the program is very clear, which is why Adodb+smarty is a gold combination of reasons. But then

Said back, simple has the simple question, does not know everybody thought that did not have, here to the display news headline length does not have the control, namely, if the length of a news headline exceeds one line to display the fan

Wai, it is automatically folded line to the next line, then the entire layout will be confused, said that we have their own situation to decide whether to use it, of course, you can also use like the previous section of the intermediary

In the same way, using a circular statement to refactor the two-dimensional array, so that it fits your purpose, how to do everyone to think about it, refer to the practice in phplib, I introduced the last section ...

Take a look at the news page again.

=============================================================
news.php
=============================================================
<?php
/*********************************************
*
* FileName: news.php
* Role: News display program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file containing Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files

$smarty = new Mysmarty (); Establish a Smarty instance object $smarty

$conn = adonewconnection ("MySQL"); Initialize ADODB
$conn->connect ("localhost", "root", "" "," News "); Connecting to a database

$NewsID = $_get["id"]; Get News Number
$NewsType = $_get["type"]; 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 a template variable name

$smarty->display ($row);
Unset ($row);

$conn->close ();
?>
=============================================================
Explain the key place, in fact, there is only one place in the news.php to explain the value.

1. $conn->getrow ($strQuery): This sentence returns a one-dimensional array, which is returned in the form of:

$array = ("Newstitle" => "xxxx", "Newscontent" => "yyyyy ...")
Understand what smarty do if you use $smarty ($array)? By the way, that's the equivalent:
$smarty->assign ("Newstitle", "xxxx");
$smarty->assign ("Newscontent", "yyyyy ...");

It's simple, really.

Now let's look at the News list:
================================================================
newslist.php
================================================================
<?php
/*********************************************
*
* FileName: newslist.php
* Role: News list Display program
*
* Author: Big bro
* email:teacherli@163.com
*
*********************************************/
Include_once ("./comm/mysmarty.class.php"); Extension class file containing Smarty
Include_once ("./comm/adodb/adodb.inc.php"); Contains ADODB master execution files

$smarty = new Mysmarty (); Establish a Smarty instance object $smarty

$conn = adonewconnection ("MySQL"); Initialize ADODB
$conn->connect ("localhost", "root", "" "," News "); Connecting to a database

$NewsID = $_get["id"]; Get News Number
$NewsType = $_get["type"]; 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 serves as a link in the news list
3. $smarty->assign ("Newslist", $rs);
Unset ($RS);
$conn->close ();

$smarty->display ("Newslist.tpl");
?>
================================================================
To explain the difference:

1. GetAll ($strQuery): This function is a good thing, its role is to $strquery query to all the data into a smarty can be recognized by a 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 done to get the parameter type=xx to link the news headlines.

Postscript:
There are several places to note when using ADODB:
1. Initialization: Initialization is not the way to use new, because it is not an object
2. Method: Basically each method is a combination of uppercase and lowercase names, this seems to be somewhat different from the *nix habits, but also different from the overall style of PHP, so

Note the case problem here.

Well, this smarty series of tutorials to the basic has been completed, I have a few of these introductory course, I hope more experts will be more experience to write out, we

Together to improve! 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!

==================


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.