PHP ADODB Introduction _php Tutorial

Source: Internet
Author: User
Tags informix interbase odbc php database set time sybase
Although PHP is a powerful tool for building WEB systems, the functionality of PHP Access databases has not been standardized, and each database uses a different and incompatible application interface (API). In order to fill this shortcoming, there is only ADODB. Once the interface for accessing the database is standardized, it is possible to hide the differences of various databases, which can be very easy to convert to different databases.
Currently the latest version of ADODB is V4.62, which supports a wide variety of databases, such as: MySQL, PostgreSQL, Interbase, Informix, Oracle, MS SQL 7, Foxpro, Access, ADO, Sybase, DB2 and General ODBC (where PostgreSQL, Informix, Sybase's driver are contributed by the development of the free software community).
One of the greatest advantages of using ADODB is that regardless of the backend database, access to the database is consistent, and the development designer does not need to learn a different set of access methods for a particular set of databases, which greatly reduces the developer's knowledge burden, the knowledge of the past can continue to use, The program code does not have to change too much when transferring the database platform.
In fact, ADODB such a development concept, is not the first, DBI appears earlier than ADODB, it provides Perl access to the database, using a consistent API call interface. I believe that using Perl + DBI friends, and then use ADODB, there will be a sense of déjà vu.
In addition, ADODB for the use of the ASP, should not be unfamiliar, this kind of friend to ADODB should be very easy to accept.
ADODB official: http://adodb.sourceforge.net/
PHP can use the least amount of effort and the most fun to build a dynamic site, to create dynamic sites we need to use the database to retrieve login account information, publish dynamic news, storage discussion area of the article. In terms of using the most common MySQL data, your company has done such a fantastic job to make your site more famous than you can imagine. Then you also find that MySQL is unable to cope with the actual workload, it is time to replace the database system.
Unfortunately, access to all databases in PHP is slightly different. Connect with MySQL you want to use mysql_connect (), and when you decide to upgrade to Oracle or Microsoft SQL Server, you must switch to Ocilogon () or Mssql_connect (), respectively. What's worse is that the parameters used for the different links are not the same, some databases say Po-tato (the potato's pronunciation), other databases say pota-to (another pronunciation of potatoes), oh ... oh, my God.
We don't give up.
When you need to ensure the portability of your program, a database packet link library called ADODB has already appeared. It provides a common application interface to communicate with all supported databases, so you don't have to give up!
ADODB is an abbreviation for active Data Object database (sorry!). Sometimes it is not very original to play computer. ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, Microsoft SQL Server, Access, FoxPro, Sybase, ODBC, and ADO, and you can Php.weblogs.com/adodb download ADODB.
Examples of MySQL
PHP is the most common database is MySQL, so I think you will like the following program code, it is linked to the MySQL server localhost, the database name is Mydab, and execute a SQL Select command query, the query results are listed in a column.
$db = mysql_connect ("localhost", "root", "password");
mysql_select_db ("MyDB", $db);
$result = mysql_query ("SELECT * FROM Employees", $DB);
if ($result = = = False) Die ("failed");
while ($fields = Mysql_fetch_row ($result)) {
For ($i =0, $max =sizeof ($fields), $i < $max; $i + +) {
Print $fields [$i]. ' ';
}
Print "
n ";
}
The program code above is marked with a color, the first paragraph is the link, the second is the execution of the SQL instruction, the last segment is the Display field, while the loop scans each column of the results, and the For loop scans the fields for each column.
The next step is to get the same result with ADODB's program code:
Include ("adodb.inc.php");
$db = newadoconnection (' mysql ');
$db->connect ("localhost", "root", "password", "MyDB");
$result = $db->execute ("SELECT * FROM Employees");
if ($result = = = False) Die ("failed");
while (! $result->eof) {
For ($i =0, $max = $result->fieldcount (); $i < $max; $i + +)
Print $result->fields[$i]. ' ';
$result->movenext ();
Print "
n ";
}
Now instead of pointing to the Oracle database, the program code just modifies the second line to become newadoconnection (' Oracle '), let's take a look at the complete program code ...
Link to database
Include ("adodb.inc.php");
$db = newadoconnection (' mysql ');
$db->connect ("localhost", "root", "password", "MyDB");
The program code of the link is more sophisticated than the original MySQL program code, because we need to be more sophisticated. In ADODB we use object-oriented methods to manage the complexity of diverse databases, and we use different classes (class) to control different databases. If you are unfamiliar with object-oriented programming, don't worry! All complex things are hidden behind the newadoconnection () function.
To save memory, we only load the PHP program code associated with the database you are connecting to, and we do this by calling Newadoconnection (Databasedriver), which contains the mysql,mssql,oracle of the legitimate database driver, Oci8,postgres,sybase,vfp,access,ibase and many other drivers.
We then generate a new object entity from the Nexus class by calling Newadoconnection (), and finally we use the $db->connect () to connect to the database.
Execute SQL command
$result = $db->execute ("SELECT * FROM Employees");
if ($result = = = False) Die ("failed");
Transfer the SQL instruction directly to the server, and when executed successfully, execute () returns a Recordset object, and you can check the $result as listed above.
A beginner's easy-to-confuse topic is that there are two types of objects in ADODB, the link object, and the Recordset object, when do we use these objects?
The Nexus Object ($DB) is responsible for linking the database and formatting your SQL query. The Recordset object ($result) is responsible for retrieving the results and normalizing the response data into text or arrays.
The only thing I need to add is that ADODB provides many useful functions to make the insert and update instructions easier, as we'll mention in the advanced chapters.
Retrieving data
while (! $result->eof) {
For ($i =0, $max = $result->fieldcount (); $i < $max; $i + +)
Print $result->fields[$i]. ' ';
$result->movenext ();
Print "
n ";
}
The previous example of getting data is much like reading data from an archive, in each row we first check to see if the end of the file (EOF), if not to the end, loop through the fields in each column, and then move to the next line (MoveNext) and then repeat the same thing.
$result->fields[] Arrays are generated by the PHP database extension system, and some database extension systems do not index the array with field names, forcing the array to be indexed by name, using $adodb_fetch_mode's generic variables.
$ADODB _fetch_mode = Adodb_fetch_num;
$rs 1 = $db->execute (' SELECT * from table ');
$ADODB _fetch_mode = ADODB_FETCH_ASSOC;
$rs 2 = $db->execute (' SELECT * from table ');
Print_r ($rs 1->fields); Shows array ([0]=> ' V0 ', [1] = ' v1 ')
Print_r ($rs 2->fields); Shows array ([' col1 ']=> ' v0 ', [' col2 '] = ' v1 ')
As you can see in the example above, two recordsets are stored and use different fetch modes, and when the recordset is generated by execute (), it is set to $adodb_fetch_mode.
ADOConnection
Objects linked to a database, execute SQL instructions, and have a set of tool functions for standard formatting of SQL instructions, such as association and date format directives.
Other useful functions
$recordset->move ($pos) Scroll through the current data column, ADODB support the entire database to scroll forward, some databases do not support the subsequent scrolling, this will not be a problem, because you can use the staging record to the cache to emulate the scroll back.
$recordset->recordcount () returns the number of records accessed by the SQL command, and some databases return 1 because they are not supported.
$recordset->getarray () returns the result as an array.
The rs2html ($recordset) function converts the passed-in recordset to the HTML table format. The following example displays the relevant usage in bold:
Include (' adodb.inc.php ');
Include (' tohtml.inc.php '); /* Includes the rs2html function */
$conn = &adonewconnection (' mysql ');
$conn->pconnect (' localhost ', ' userid ', ' Password ', ' database ');
$rs = $conn->execute (' SELECT * from table ');
Rs2html ($RS); /* Recordset to HTML table */
There are many other useful functions listed in the file, which can be found at the following URLs http://php.weblogs.com/adodb_manual
Advanced Topics
New and updated
Suppose you want to add the following data to the database.
ID = 3
Thedate=mktime (0,0,0,8,31,2001)/* 31st August 2001 */
note= Sugar Why don ' t we call it off
When you switch to a different database, you may not be able to add data.
The first problem is that each database has its own default date format, MySQL uses the YYYY-MM-DD format, and other databases have different default formats, and ADODB provides dbdate () functions to convert the date-default format between different databases.
The second issue is the single quotation mark (don ' t) notation, which can be used directly in MySQL (not), but in other databases such as Sybase, Access, and Microsoft SQL Server, it is represented in two single quotes (don ' t), Qstr () function to resolve this problem.
How do we use these functions? Just like this:
$sql = "INSERT into table (ID, Thedate,note) VALUES ("
. $ID. ','
. $db->dbdate ($TheDate). ', '
. $db->qstr ($Note). ")";
$db->execute ($sql);
ADODB also has the $connection->affected_rows () function, which returns the number of data columns affected by the last update or delete instruction, and the $recordset->insert_id () function, Back to the last data column number that was automatically generated by the insert instruction, you are forewarned that there are no databases that provide these two functions.
Metatypes
You can get more information about the field, and Fetchfield ($fieldoffset) returns the 3 properties of the object through the recordset: Name,type,max_length.
To illustrate:
$recordset = $conn->execute ("Select adate from table");
$f 0 = $recordset->fetchfield (0);
The result $f0->name content is ' adata ', $f 0->type will be ' date ', if max_length do not know, its content will be-1.
One problem with different databases is that each database has a different name for the same data type, such as that the timestamp type is called DateTime in a database, and the other database is called time, so ADODB provides Metatype ($type, $max _length) function to standardize the following data types:
C:character and varchar types
X:text or long character (eg. more than 255 bytes wide).
B:blob or binary image
D:date
T:timestamp
L:logical (Boolean)
I:integer
N:numeric (float, double, money)
In the previous example,
$recordset = $conn->execute ("Select adate from table");
$f 0 = $recordset->fetchfield (0);
$type = $recordset->metatype ($f 0->type, $f 0->max_length);
Print $type; /* Should print ' D ' */
Limit and top support for select directives
ADODB has a $connection->selectlimit ($sql, $nrows, $offset) function that lets you take a partial collection of the recordset, using the Select top usage in Microsoft products, and PostgreSQL and MySQL in the Select ... The advantage of the limit usage is that even if the original database does not provide this usage, this function also simulates providing that usage.
Quick Access Support
ADODB allows you to stage the recordset's data in your file system, and in $connection->cacheexecute ($ secs2cache, $sql) and $connection Cacheselectlimit ($secs 2cache, $sql, $nrows, $offset) wait for the set time interval to arrive, then really do the database query to save time.
PHP4 Session Support
ADODB also supports PHP4 session handler, you can store your session variables in the database, related functions please refer to Http://php.weblogs.com/adodb-sessions
Encourage commercial use
If you plan to write commercial PHP applications to sell, you can also use ADODB, we publish ADODB according to the GPL, which means you can legitimately refer to the commercial application and retain ownership of your program code. Strongly encourage the commercial application of ADODB, and we ourselves are using it for this reason.

http://www.bkjia.com/PHPjc/320058.html www.bkjia.com true http://www.bkjia.com/PHPjc/320058.html techarticle Although PHP is a powerful tool for building WEB systems, the functionality of PHP Access databases has not been standardized, and each database uses a different and incompatible application ...

  • 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.