Pear DB Novice Getting Started Guide

xiaoxiao2021-03-06  26

Pear DB Novice Getting Started (Original: "Quick Start Guide To Pear DB")

Translation: Gangchen@wiscom.com.cn

table of Contents

1 Introduction----------------------------------------------- --------------------------------------2

2. Download, install PEAR ---------------------------------------------------------------------------------------------------------- -----------------------------2

3 Using Pear DB ---------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------2

3.1.1 Connection, disconnect the database

3.1.2 Executing the Database

3.1.3 Get the data of SELECT

3.1.3.1 Functions for obtaining data

3.1.3.2 Select the format of obtaining data

3.1.3.3 Setting the format for obtaining data

3.1.3.4 Control Getting Data Quantity

3.1.3.5 Clear results, release variables

3.1.4 Quick Retrieve Data

3.1.5 Get more information from query (NumRows, Numcols, AffectedRows, TableInfo)

3.1.6 Automatic growth (SEQUENCES)

3.1.7 Prepare & Execute / ExcuteMultiple

3.1.8 AutoCommit, Commit and Rollback

4. A list of available methods ------------------------------------------- ------------------------------ 10

5 Error handling mechanism ---------------------------------------------- ---------------------------- 12

5.1 Get an error message from Pear DB ERROR

5.2 Debug Pear DB ErrorS

5.3 Automatic handling of errors

1 Introduction

This is a guiding how we use PEAR DB extension. Pear DB provides such a series of classes:

N database abstraction

N Advanced Error Processing Mechanism

N and other

2. Download, install PEAR

Since the Pear project is still in the development of intensive drums, the best way to get it is from CVS (PEAR DB issuing package has followed PHP)

4.0.6

The release is bundled later). So, we only need to put the root directory of the PEAR in the php.ini profile include_path. You can also set this setting: _SET ('include_path', '/ pear_base_dir').

The following is a STRP BY Step example:

Store the directory of the PEAR:

# cd / usr / local / lib

Log in with "phpfi" password:

# CVS -D: PServer: cvsread@cvs.php.net: / repository login

Get all PEAR files with the following command, and can also be used to update files that have been downloaded. Other parameters are: "Today", "Last Month", etc. I recommend "Last Week" parameters because general BUGS submission and modification are once a week.

# CVS -D: PServer: cvsread@cvs.php.net: / repository export -d "Last Week" PHP4 / PEAR Edit php.ini file plus the following paragraph 1 in the include_path: / usr / local / lib / php4 / pear If there is no modified permissions, you can implement this statement in the code: INI_SET ('Include_path', 'Path_TO_Pear');

Get full documentation for PHP CVS

Note Pear DB required PHP version

4.0.4

These, and some other packages in PEAR, such as: XML Parser of the Pear Installer Script requires PHP4.0.5 or higher.

3. Using PEAR DB

3.1 Connection, disconnect the database

getMessage ());} .. .. // You can disconnect from the database with: $ dB-> disconnect ();?>

Data Source ($ DSN parameters in the previous example) have the following format: (copy from Pear / DB.php ParsedSn method)

* Phptype: Database backend used in PHP (mysql, odbc etc.) * dbsyntax: Database used with regards to SQL syntax etc. * protocol: Communication protocol to use (tcp, unix etc.) * hostspec: Host specification (hostname [: port]) * database: Database to use on the DBMS server * username: User name for login * password: password for login * * The format of the supplied DSN is in its fullest form: * * phptype (dbsyntax): // username : password @ protocol hostspec / database * * Most variations are allowed: * * phptype: // username: password @ protocol hostspec: 110 // usr / db_file.db * phptype: // username: password @ hostspec / database_name * phptype: // username: password @ hostspec * phptype: // username @ hostspec * phptype: // hostspec / database * phptype: // hostspec * phptype (dbsyntax) * phptype now supports database contains (in phptype DSN section):

MySQL -> Mysql Pgsql -> PostgreSQL IBase -> Interbase Msql -> Mini SQL MSSQL -> Microsoft SQL Server OCI8 -> Oracle

7/8/8

I odbc -> ODBC (OPEN DATABASE CONNECTIVITY) SYBASE -> Sybase IFX -> Informix Fbsql -> Frontbase

Note that all database features are supported,

The root directory> / db / status gets a detailed list.

3.2 Execute Database

query will return // a db Result Object ON Success. // Else IT SIMPLY WILL RETURN A DB_OK / / ON FAILURE IT WILL RETURN A DB ERROR Object. $ Result = $ DB-> Query ($ SQL); // ALWAYS CHECK THAT $ Result Is Not An Error IF (DB :: ISERROR ($ Result) {Die ($ result-> getMessage ());} ....?>

3.3 Get the data of SELECT

3.3.1 Getting Data Functions

fetchrow ()) {$ ID = $ Row [0];}?>

In addition to fetchrow (), you can also use Fetchinto () to insert the value of $ ROW directly.

3.3.2 Select the format of the acquisition data

The acquisition mode has DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC and DB_FETCHMODE_OBJECT.

Example of the result of the acquisition data method returned:

query ('select ID, name, email from users "); $ row = $ r => = = db_fetchmode_ordred // The default behavior is TO RETURN An Ordered Array. $ ROW = Array (0 => , 1 => , 2 => ); $ ID = $ row [0]; // with $ mode = DB_FETCHMODE_ASSOC // Returns An Associative Array with Column Names as Array Keys: $ row = array ('id' => , 'name' => , 'email' => ); $ ID = $ row [' id '; // with $ mode = db_fetchmode_Object // Returns A db_row Object with column names as Properties: $ Row = db_row object ([id] => , [name] => , [email] => ) $ ID = $ row- > ID;?>

3.3.3 Setting the format for obtaining data

You can use the fetchrow () / fetchinto () method or set a default mode for your DB instance.

fetchrow (db_fetchmode_assoc) {[..]} while ($ results-> fetchinto ($ row, db_fetchmode_assoc)) {[..]} // 2) Set The Mode for All Calls: $ db = db :: connect ($ dsn); // this will set a default fetchmode for this pear db instance // (for all queries) DB-> setfetchmode (db_fetchmode_assoc); $ result = $ db-> query (...); while ($ row = $ result-> fetchrow ()) {$ ID = $ row ['id'];}?> 3.3.4 Control Getting Data Quantity

At the same time, PEAR DB obtains data with additional parameters, you can use a numeric parameter to get the required amount of data. This is especially useful at this time you just need to get a part of the data (such as when making a paging program)

3.3.5 Clear results, release variables

When you complete the query, you can use the free () method to end:

query ('selection * from clients'); while ($ row = $ result-> fetchrow ()) {...} $ results-> free ();? >

3.4 Quick Retrieve Data

When you no longer want to use the fetchrow () method to get the data, Pear DB provides some special ways to return to the desired data via the SQL statement. These methods are: getone, getrow, getCol, getAssoc and getall. There are some examples:

getone ('select count (id) from clients'); // ------------------ ----------------------------------------- // GetRow Will Fetch The first row and Return It as an array $ sql = 'select name, address, phone from clients where id = 1'; if (is_ARRAY ($ row)) {list ($ name, $ address, $ Phone) = $ row;} // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------- // Getcol Will Return an array with the data of the // selected column. It accepts the column number to retrieve // ​​as the second param. // the next sentence could return for example: // $ all_client_names = array ('stig', 'jon', 'color); $ all_client_names = $ db-> getcol (' select name from clients'); // -------------------------------------------------- -------- // Other Functio NS Are: getAssoc () and getall (). // for the moment refer to their in-line documentation // at pear / db / common.php // --------------- ------------------------------------------?> "Get * ( ) Series Methods "can do a lot of things for you, including: initiating a query, getting data and clearance results. Note that all PEAR DB functions may return a Pear DB_ERROR object.

3.5 Get more information from query (Numrows, Numcols, AffectedRows, TableInfo)

More useful data information can be obtained from the query result via the PEAR DB. These methods are:

NumRows (): The number of all data is returned through a "SELECT" query.

Numcols (): Returns all columns through a "SELECT" query.

AffectedRows (): Operate through ("INSERT", "Update" or "delete") operation returns all affected data lines.

TableInfo (): Returns an array containing data information through a "SELECT" query.

Example:

query ($ sql); // Don't forget to check if The Returned Result from Your // Action Is A Pear Error Object. If You Get A Error Message // Like 'DB_ERROR: DATABASE NOT CAPABASE BACKEND DOESN' 'Support this action. /// Number of Rows Echo $ RES-> NumRows (); // Number of Cols Echo $ RES-> NumCols (); // Table Info Print_R ($ RES-> TableInfo ()); // Affected Rows $ SQL = "Delete from Clients "; // Remember That this Statement Won't return A Result Object $ db-> query ($ SQL); Echo 'i Have Deleted'. $ db-> affectedRows (). 'clients';> 3.6 Automatic growth (Sequences)

SEQUENCES provides a unique ID identifier for the data line. If you are familiar with MySQL, you can imagine it as Auto_Increment. It is very simple, first you get an ID, then insert the data you need to record in this ID. You can set more Sequences for your table, just ensure the same sequence in any special table.

nextid ('mysequence'); // use the id in your insert query $ RES = $ DB-> Query ("INSERT INTO MyTable (ID, Text) Values ​​($ ID, 'FOO')"); ...?>

3.7 Prepare & Execute / Excutemultiple

prepare ("Insert Into Numbers Values ​​(,,)"); Foreach ($ alldata as $ row) {$ dbh-> Execute ($ st, $ row);} // here's an example of a file discounter: $ myfile = "/tmp/image.jpg"; $ st = $ dbh-> prepare ( 'INSERT IMAGES (, &)'); $ dbh-> EXECUTE ($ Sth, Array ("this is me", $ myfile); // after i commit a bugfix That i Have ON My Laptop, You Can Use // Parameter Arrays in the getXXXMETHODS TOO: $ VER = $ dbh-> getone ("Select StableVersion from Packages Where Name =", Array ($ package));> 3.8 AutoCommit, Commit and Rollback

4. List of available methods

setErrorhandling (); $ db-> setfetchmode (); // information $ db-> affectedRows (); $ dB-> TableInfo (); // Database manipulation $ db-> query (); // Data fetch $ db-> nextid (); $ db-> getone (); $ db-> getrow (); $ db-> getcol (); $ db-> getAssoc (); $ dB-> getAll (); // Place Holders and Execute Related $ db-> quote (); $ db-> prepare (); $ db-> execute (); $ db-> executemultiple (); // Transactions $ db-> autocommit (); $ db-> commit (); $ db-> rollback (); // disconnection $ db-> disconnect (); / * * from db_result Objects * / // Get The Object with, IE: $ RES = $ dB- > Query ('SELECT * from fom foo'); // Data Fetch $ res-> fetchrow (); $ res-> fetchinto (); // result info $ res-> numcols (); $ r-> nuMrows () $ RES-> TableInfo (); // free $ res-> free (); / * from db_error objects * / // Get the object with, ie: $ error = $ db-> query ('select * from NO_TABLE '); $ Error-> getMessage (); $ error-> getDebuginfo (); $ Error-> TOSTRING ();?> 5. Error handling mechanism

5.1. Get the error message from Pear DB Error

All errors returned from Pear DB are pear errors. This has a method to collect:

query ('select * from no_table'); if (db :: iesrror ($ ●)) {// Get the portable error String Echo $ r $ r -> getMessage () ;}?>

4.2 Debug Pear DB Errors

Pear DB uses a lightweight error message system to report an error to the user. It has brought great advantages to other languages, simply translating the error message into other languages ​​or for a special error. But for developers, these tips are provided with very useful information. If you want to get a real data to process an error, you can use the getDebuginfo () method:

Query ($ SQL))) {// Get the native backnd error // and the last query echo $ RES-> getDebuginfo ();}?> The error prompt is printed by a PHP function. This mechanism in the PEAR is blocked. But sometimes you may need to capture some error messages in your code. You can use the set_error_handler PHP function to get information from PHP Manual. Simple example:

?

5.3 Automatic handling of errors

As you can see, Pear DB provides a wide range of error detection and reporting mechanisms, which must be checked by the returned data results, is wrong. Pear DB also takes care of us to avoid this painful job, providing a flexible system that automatically calls the corresponding measures when an error occurs.

These possible measures include:

Returns the error object (pear_error_return). This is the default.

Print error (pear_error_print)

Print the error message and ignore the execution (pear_ERROR_DIE)

Use a PHP function trigger_error () to list the error (pear_error_trigger)

Pass the error object to a function or class (pear_error_callback)

Simple example:

query ('select id from no_table'); // at this point the execution is aborted and the error message is raisen ...?>

Advanced example:

? getMessage (). "/ n". $ error_obj-> getDebuginfo ()); // Dump a silly message if the site is in production} else {Die ('Sorry You Request CAN NOTBE Processed Now. Try Again Later ');}}}}} Require_once' db.php '; // ON Error, Call The "Handle_Pear_ERROR" Function Back // You Can Also Use An Object As Pear Error Handler SO: / / setErrorHandling (PEAR_ERROR_CALLBACK, array ($ object, 'method_name'); PEAR :: setErrorHandling (PEAR_ERROR_CALLBACK, 'handle_pear_error'); $ db = DB :: connect ( 'pgsql: // postgres @ localhost / site_db'); $ res = $ Db-> query ('select id from no_table'); // at this point the execution is aborted and the "handle_pear_error" // function is caled with the error Object As ITS First Argument W Hile ($ row = $ r-> fetchrow ()) {...} ...?> The following provides a good idea for the extension error mechanism:

转载请注明原文地址:https://www.9cbs.com/read-69527.html

New Post(0)