Smarty practical teaching examples (3. Connecting to the database using ADODB)
Due to work reasons, I have been very busy in the past two months, so I did not complete this tutorial in time. It just so happens that I don’t have to work overtime today on Saturday, so take some time to complete it! At the beginning When making a new tutorial, I first corrected some errors in the tutorial I wrote before. I would like to thank brother nesta2001zhang for finding out some errors in the article, otherwise it would be really ignored by others.
Critical "misleading people" (I'm really ashamed to say that after my first draft was released, I found a lot of problems. Later, sometimes there were also errors in the revised document. It really shouldn't be done. ..)
In the last few 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 effect of the first method is no different from the second method, and that I have debugged several programs 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 our ADODB here It is not Microsoft's database operation component, but a set of database operation libraries written in PHP language. Let us first take a look at what advantages it has.
1. Database written in standard SQL statements The execution code 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 big deal for people who switch from ASP to PHP Good news, 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 database caching Query, maximize the speed of querying the database.
5. Other practical functions.
Although it has many advantages, because this class library is very huge, its main execution class alone is 107K, so if you consider execution efficiency, you must think about it seriously. But to be honest, Its
function is still very powerful, and it has many very practical functions. Using these functions, it is very convenient to achieve the functions we want. So for those bosses who do not have special requirements, please do not use it
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?
Decompress 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 decompress it. After decompression is complete, 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 is: the traditional way. 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.
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, password is oraclePasswd, database server is localhost, database is oradb dsn Write like this:
$dsn = "oracle://oracleUser:OraclePasswd@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 the ADOConnection class, the other is the ADORecordSet class, which has been used in ASP People will understand their meaning when they see these two classes.
ADOConnection refers to the database connection class, and ADORecordSet refers to the data set class returned by ADOConnection executing the query statement. For relevant information, you can check the ADODB
class manual .
3. Basic functions:
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));
}
========================================== ==============================================
This line is What does that 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 article of news here");
...
This form, but if we don't need to control the title, we will be 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 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 one 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. Let’s take 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 integrity of the program, you still have to close the database at the end of the page.
About 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(): Contained Number of records. 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. It can return a drop-down menu (or multi-select box) with name=$name!!! Of course, it is an HTML string, which is a command Exciting stuff, $name refers to the name attribute of
option, $default_str is the string selected by default, $blank1stItem indicates whether the first item is empty, $multiple_select indicates whether it is a multiple selection box, and we get this
After adding the string, you can use $smarty->("TemplateVar", "GetMenuStr") to enter a drop-down list (or multiple boxes) at the "TemplateVar" of the template
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);
}
}
The above introduces the use of shimokita glory days ADODB combined with SMARTY ~ super powerful, including the content of shimokita glory days. I hope it will be helpful to friends who are interested in PHP tutorials.