Home >Backend Development >PHP Tutorial >Smarty Example Tutorial Example_PHP Tutorial

Smarty Example Tutorial Example_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 16:11:05742browse


Smarty practical teaching examples (3. Connecting to the database using ADODB)

I have been very busy in the past two months due to work reasons, so I did not complete this tutorial in time. It just so happened that I didn’t have to work overtime today on Saturday, so I took the time to complete it. Just do it! When starting a new tutorial, I

first corrected some errors in the tutorial I wrote before. I would like to thank brother nesta2001zhang for finding out the article. There are some mistakes in it, otherwise others

would really criticize me as "misleading people" (I am really ashamed to say that after my first draft was released, I found a lot of problems, and later revised it some time) There were actually errors in the final file, which really shouldn’t be done

This...)
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 change it like this? Because the second method is clearer, in fact the first method The effect of the method is no different from the second method, and I have debugged those programs before,

without any problems.
Okay, let’s talk about ADODB today. Speaking of ADODB, those who have done ASP may know the ADO component of the WINDOWS platform, but the ADODB we have here is not the database operation component of Microsoft, but a set of database operation class libraries written in PHP language. , let us first take a look at what advantages it has.
1. The database execution code written in standard SQL statements does not need to change the source program when transplanting the database, which means that it can support a variety of databases , including ACCESS.
2. Provides syntax functions similar to Microsoft ADODB. This is a great boon for people who switch from ASP to PHP. Many of its operations are similar to ADODB in WINDOWS.
3. You can generate the two-dimensional array required for Smarty loops, which will simplify smarty development. I will demonstrate this to you later.
4. Support cached queries of the database to maximize the speed of querying the database.
5. Other practical functions.
Although it has many advantages, because this class library is very large, its main execution class alone is 107K, so if you consider execution efficiency, you must think about it seriously. But to be honest, its

functions are still very powerful and have many very practical functions. Using these functions, we can achieve the functions we want very conveniently. So there are no special requirements for those bosses Don’t use it if you don’t



1. How to get ADODB? What is its operating environment?
From http://sourceforge.net/project/show... hp4.0.5 or above.
2. How to install ADODB?
Unzip the downloaded compressed file. Note: The format you downloaded is ADODB.tar.gz, which is the compression format of Linux. Under Windows, you can use winrar to compress it.

Execute the decompression. After decompression is completed, copy the directory to the adodb directory of the specified directory. Like I copied it to /comm/adodb/ in the example.
3. How to call ADODB?
Use include_once ("./comm/adodb/adodb.inc.php"); This line goes without saying, right? Contains the main file for ADODB.
4. How to use ADODB?
1. Initialization:
ADODB is initialized using the statement $conn = ADONewConnection();. There are two ways to initialize ADODB:
The first way The method is: traditional method. I'll call it that for now. The method it uses to establish a new connection is very similar to the standard connection method in PHP:
$conn = new ADONewConnection($dbDriver);
$conn->Connect($host, $user, $passwd, $db);
Simple, right? If you have used the db class in phplib, you should be familiar with it.

The second method: Use the dsn method, which writes the database connection statement into one statement for initialization. The way to write dsn is as follows: $dsn =

"DBType://User :Passwd@Host/DBName"; where DBType represents the database type, User represents the user name, Passwd is the password, Host is the server name, DBName is the database name

, like this I use the oracle database, user name: oracleUser , the password is oraclePasswd, the database server is localhost, and the dsn of the database is oradb is written like this:
$dsn = "oracle://oracleUserraclePasswd@localhost/oradb";
$conn = new ADONewConnection($dsn);
This method may be more interesting to programmers who have switched from ASP.

Both methods can be used, it depends on personal habits.

2. Related concepts:
There are two basic classes for using ADODB, one is ADOConnection class, the other is the ADORecordSet class. People who have used ASP will understand its meaning when they see these two classes.

ADOConnection refers to the database connection class, and ADORecordSet refers to the query statement executed by ADOConnection. For the returned data set class, you can check the ADODB

class manual for related information.

3. Basic functions:

The related methods of the ADOConnection class are:
1.Connect: Database connection method, which we introduced above. For mysql, there is also PConnect, which is the same as the usage in PHP language
2.Execute($sql): Execute the query statement and return an ADORecordSet class.
3.GetOne($sql): Returns the first field of the first row
4.GetAll($sql): Returns all data. This function is very useful. Do you remember that when I wrote about the input of the news list in the previous tutorial, I had to make the

news list that needs to be displayed on the page into a two-dimensional array? This is the sentence:
============================================ ===========================================
while($db ->next_record())
{
$array[] = array("NewsID" => $db->f("iNewsID"),
"NewsTitle" => csubstr( $db->f("vcNewsTitle"), 0, 20));
}
========================== ================================================== ==========
What does this line mean? It is to generate the news example table to be displayed
$array[0] = array("NewsID"=>1, "NewsTitle"=>"The first news item here");
$array[1 ] = array("NewsID"=>2, "NewsTitle"=>"The second news item here");
...
This form, but if we don’t need to control the title , we are lucky in ADODB, we can write like this:
================================== =================================================
$strQuery = "select iNews, vcNewsTitle from tb_news_ch";
$array = &$conn->GetAll($strQuery);//Pay attention to this statement
$smarty->assign("News_CH ", $array);
unset($array);
================================ ==================================================
Of course, $conn here should have been initialized. I wonder if you understand it? It turns out that the two-dimensional data I want to create manually can just use GetAll here! ! ! This is also one of the reasons why some people say that ADODB+Smarty is an 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

sentence, which has the same effect as the limit in the mysql statement. Here is a simple example:
$rs = $conn->SelectLimit("select iNewsID, vcNewsTitle from tb_news_CH", 5, 1);
Do you understand? Saved in $rs are the 5 records starting from the first record in the database. We know that the Oracle database does not support the use of limit in SQL statements, but if we use ADODB, then this problem will be much easier to solve!
5.Close(): Close the database. Although PHP will automatically close when the page ends, for the sake of the integrity of the program, you still have to close the database at the end of the page.

Regarding 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 contained. This record determines the total number of records in the data set.
3. GetMenu($name, [$default_str=''], [$blank1stItem=true], [$multiple_select= false], [$size=0], [$moreAttr='']) is a very good

function, which can return a drop-down menu (or multi-select box) with name=$name! !!Of course, it is an HTML string, which is an exciting thing. $name refers to the name attribute of

option, $default_str is the default selected string, and $blank1stItem points out Whether the first item is empty, $multiple_select indicates whether it is a multi-select box, and after we get this

string, we can use $smarty->("TemplateVar", "GetMenuStr") to add it to the template Enter a drop-down list (or multiple boxes) at "TemplateVar"
4. MoveNext(): Let's look at a piece of 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 very similar to the one in MS ADODB!
5. MoveFirst( ), MoveLast(), Move($to): Same, you can know what it means by looking at the function name.
6. FetchRow(): Returns a row, 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 implements the same function as 4, but looks more in line with PHP's habits, while 4's habits look more like MS ADODB's approach.

7.GetArray($num): Returns $num rows of data in the data set and combines them into a two-dimensional array. We will use this method in the example index.php.

8 . Close(): Same as mysql_free_result($rs); clear content occupation.

Okay, the preliminary functions are introduced here, which is enough for us! In fact, ADODB has many practical technologies, including For formatting date and time, formatting query statements, output tables, more advanced

point Cache query, query with parameters, etc., you can check the manual by yourself.

Let’s start learning our program, it is also the Web program. I reorganized the comm directory and re-encapsulated Smarty in order to improve efficiency

. mySmarty.class.php is the encapsulated class, which inherits from Smarty, so in the future, only the new class MySmarty will be called in all program files. Let’s take a look at the directory structure first:
+Web (site root directory)

|----+comm (Smarty related documents Directory)

| |----+smarty (Smarty original file directory)
| |----+adodb (adodb original file directory)
| |-----mySmarty .class.php (extended smarty file)
| |-----csubstr.inc (intercept Chinese characters)

|----+cache (Smarty cache directory, under *nix Guaranteed read and write permissions)

|----+templates (site template file storage directory)

| |----header.tpl (page header template file)
|----index.tpl (site home page template file)
| |----foot.tpl (page footer template file)
| |----news.tpl (news page template file)

|
|----+templates_c (the directory where template files are stored after compilation, read and write permissions are guaranteed under *nix)

|----+css (site CSS file directory)

|----+image (site picture directory)

|----+media (site Flash animation storage directory)

|- ---indexbak.htm (original rendering of homepage)

|----newsbak,htm (original rendering of news page)

|----index.php (Smarty homepage Program file)

|----news.php (Smarty news display file)

|----newsList.php (display news list)

|- ---Routine description.txt (this document)

Compared to the previous two tutorials, the comm directory has been reorganized, and the other file structures have not changed. The entire site is similar to the previous two tutorials. Speaking of, the only changes are the comm directory and

index.php and news.php. At the same time, the news list is added. You can click "Domestic News" and "International News" in the page after index.php is executed. , "Entertainment News" to view their respective

news lists respectively. Let's take a look at index.php first:

================ ======================================
index.php
=== ================================================== =
/*******************************************
*
* File name: index.php
* Function: Display example program
*
* Author: Senior Brother
* Email: teacherli@163.com
*
**** *****************************************/
include_once("./comm/mySmarty.class.php"); //Contains smarty’s extension class file
include_once( "./comm/adodb/adodb.inc.php"); //Include ADODB main executable file
include_once("./comm/csubstr.inc"); //Include Chinese interception class

define ("NEWS_NUM", 5); //Define the number displayed in the news list

$smarty = new MySmarty(); //Create a smarty instance object $smarty

1. $conn = ADONewConnection ("mysql"); //Initialize ADODB
2. $conn->Connect("localhost", "root", "", "News"); //Connect to the database


//The domestic news part 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);


//The international news part is processed 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 part 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 index.tpl template located under ./templates
$smarty->display("index.tpl");
?>
============== ================================================== =============
Similarly, I have added numbers in key places. Let’s explain their meanings:

1. Create a connection object $conn , what everyone should pay attention to here is that its initial appearance does not appear in the form of $conn = new ADONewConnection($dbType), that is to say

, ADONewConnection is not a class, you cannot use new to modify it. Initialization. If you look at its source code, you will understand that this is just a function.

2. Needless to say, right? Open a News database, the host is: localhost, the user name is root, the password is ""

3. A query statement, note that the query field must be used here AS keyword to re-identify, the name is the name of the template variable you set in the template.

4. Use Execute to execute this query, and the result returns a RecordSet data set

5. Here There is a method: $rs->GetArray($num) This is introduced above. It returns $num rows from the $rs data set. The result is a two-dimensional number that can be recognized by Smarty

Data. In this way, ADODB automatically builds such a structure for us, and in our previous examples, we used a loop to build such an array.

6. I don’t even need this sentence. Did you say that?

7. Close related resources in the memory.

As you can see, there are no while statements in the entire program, and the overall structure of the program is very clear. This is The reason why ADODB+Smarty is the golden combination. But then again, simplicity has simple problems. I wonder if you have thought about it. There is no control over the length of the news titles displayed here, that is to say, If the length of a certain news title exceeds the display range of one line

, it will automatically wrap to the next line, and the entire layout will be messed up. It is up to you to decide whether to use this method according to your own situation. Of course, you can also use a loop statement to reconstruct this two-dimensional array to make it fit your purpose, as introduced in the previous section

. You can think about it yourself. Please refer to PHPLIB I introduced the method in the previous section...

Let’s take a look at the news page again

==================== ==========================================
news.php
================================================== ============
/*******************************************
*
* File name: news.php
* Function: News display program
*
* Author: Senior Brother
* Email: teacherli@163.com
*
**** *****************************************/
include_once("./comm/mySmarty.class.php"); // Contains smarty’s extension class file
include_once("./comm/adodb/adodb.inc.php"); //Includes the ADODB main executable file

$smarty = new MySmarty(); //Create smarty instance object $smarty

$conn = ADONewConnection("mysql"); //Initialize ADODB
$conn->Connect("localhost", "root", "", "News") ; //Connect to the database

$NewsID = $_GET["id"]; //Get the news number
$NewsType = $_GET["type"]; //The type of news to be displayed
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 the template variable name

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

$conn->Close();
?>
================ ==============================================
Description Let’s talk about the key points. In fact, there is only one place in news.php where the value is explained.

1. $conn->GetRow($strQuery): This sentence returns a one-dimensional array. The form is:

$array = ("NewsTitle"=>"xxxx", "NewsContent"=>"yyyyy...")
Understand if you use $smarty($array) after Smarty Does it do anything? By the way, it is equivalent to:
$smarty->assign("NewsTitle", "xxxx");
$smarty->assign("NewsContent", "yyyyy..." );

Simple, it’s really simple

Let’s take a look at the news list:
==================== ============================================
newsList.php
================================================== =================
/*******************************************
*
* File name: newsList.php
* Function: News list display program
*
* Author: Senior Brother
* Email: teacherli@163.com
*
*** ******************************************/
include_once("./comm/mySmarty.class.php "); //Include smarty's extension class file
include_once("./comm/adodb/adodb.inc.php"); //Include ADODB main executable file

$smarty = new MySmarty( ); //Create smarty instance object $smarty

$conn = ADONewConnection("mysql"); //Initialize ADODB
$conn->Connect("localhost", "root", "" , "News"); //Connect to the database

$NewsID = $_GET["id"]; //Get the news number
$NewsType = $_GET["type"]; //To display News type
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 the link in the news list
3. $smarty->assign("NewsList", $rs);
unset( $rs);
$conn->close();

$smarty->display("newsList.tpl");
?>
====== ================================================== =========
Let’s explain them separately:

1. GetAll($strQuery): This function is a good thing. Its function is to get all the data queried by $strQuery. The data is combined into a two-dimensional array that can be recognized by Smarty.

Remember: it returns a two-dimensional array instead of a RecordSet, so you can use it directly in 3 places in the program.
2. This is done to require the GET parameter type=XX when linking to news titles

Postscript:
There are several things you should pay attention to when using ADODB:
1. Initialization: The way to initialize is not to use new, because it is not an object
2. Method: Basically every method has a mixed-case name starting with a capital letter. This seems to be somewhat different from the *NIX habit, and also different from The overall style of PHP, so

pay attention to the capitalization issue here.

Okay, this Smarty series of tutorials has basically been completed here, and these few of my basic tutorials are I hope more experts will write down more experiences and let us all

improve together! Because the company does not allow opening QQ, if you want to communicate with me, please add my MSN :teacherli@ceua.org, everyone is welcome to discuss together!

(Source: Viphot)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314055.htmlTechArticleSmarty Example Teaching Example (3. Using ADODB to connect to the database) In the first two months, I have been busy due to work reasons. I'm busy, so I didn't finish this tutorial in time. It just so happens that I don't have to work overtime today on Saturday...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn