ADODB class using _php tutorials

Source: Internet
Author: User
Tags localhost mysql php database sybase

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 , but in other databases such as Sybase, Access, Microsoft SQL Server, The qstr () function resolves this problem by using two single quotation marks ("T").

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 ($secs 2cache, $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/317254.html www.bkjia.com true http://www.bkjia.com/PHPjc/317254.html techarticle MySQL example PHP is the most common database is MySQL, so I think you will like the following program code, it links to localhost MySQL server, database name is Mydab, and ...

  • Related Article

    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.