Pear DB

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Pear DB

• PHP Include & PHP Include_once


• The “include” php statement is used to include other files into
a PHP file.
• It has two variations, include and include_once.  Include_once
is ignored by the PHP interpreter if the file to be included.
• The include statement has the following syntax
• <?php include 'file_name'; ?>
• The include_once statement has the following syntax
• <?php include_once 'file_name'; ?>
• HERE,
• “Include/include_once” is the statement that includes file
• “'file_name'” is the name of the file to be included.
• Example:
• Header.php

• <a href="/index.php">Home</a> <a


href="/aboutus.php">About us</a>
index.php
• <?php include 'header.php'; ?>
• PHP Require & PHP require_once
• The require statement has two variations, require and require_once.
• The require/require_once statement is used to include file.
• Require_once is ignored if the required file has already been added by any
of the four include statements.
• It has the following syntax
• <?php require 'file_name'; ?>
• <?php require_once 'file_name'; ?>
• PEAR DB Basics:
•  
• PEAR (PHP Extension and Application Repository) is a framework and
distribution system for reusable PHP classes, libraries and modules. One of
its most popular packages is PEAR DB, the database abstraction layer
created by this project. DB provides portability features that enable
programs written for one database to work with other databases.
• PEAR DB library (which comes with PHP)
• -- to connect to a database,
• -- issue queries,
• -- check for errors, and
• -- transform the results of queries into HTML.
• The library is object-oriented, with a mixture of class methods
(DB::connect( ), DB::iserror( )) and object methods ($db->query( ), $q-
>fetchInto( )).
• <?php // connect require_once('DB.php');
• $db = DB::connect("mysql://librarian:passw0rd@localhost/library");
• if (DB::iserror($db))
• {
• die($db->getMessage( ));
• }
• // issue the query $sql = "SELECTbooks.title,books.pub_year,authors.name
FROM books, authors WHERE books.authorid=authors.authorid ORDER BY
books.pub_year ASC";
• $q = $db->query($sql);
• if (DB::iserror($q))
• {
• die($q->getMessage( )); }
• // generate the table
• while ($q->fetchInto($row)) { ?> <tr><td><?= $row[0] ?></td> <td><?=
$row[1] ?></td> <td><?= $row[2] ?></td> </tr> <?php } ?>
• Data Source Names
•  
• A data source name (DSN) is a string that specifies
•  
• Where the database is located,
• What kind of database it is,
• The username and password to use
• When connecting to the database, and more.
•  
• The components of a DSN are assembled into a URL-like
• string:
• type(dbsyntax)://username:password@protocol+hostspec/database
•  
• PHP database types
• Name Database
• Mysql MySQL
• Pgsql PostgreSQL
• Mssql Microsoft SQL Server
• Odbc ODBC
• , Inc. All rights reserved.
•  
•  
• These are some sample valid data source names:
•  
• mysql:///webdb
• mysql://localhost/webdb
• mysql://bondview@localhost/webdb
• mysql://bondview@tcp+localhost/webdb
• mysql://bondview:007@localhost/webdb
• Connecting:

•  Once you have a DSN, create a connection to the database using the connect( ) method.
•  $db = DB::connect(DSN [, options ]);
•  The options value can either be Boolean, indicating whether or not the connection is to be
persistent, or an array of options settings.

•  Error Checking
•  
• PEAR DB methods return DB_ERROR if an error occurs.
•  
• $db = DB::connect($datasource);
•  
• if (DB::isError($db)) {
• die($db->getMessage( ));
• }
• The DB::isError( ) method returns true if an error occurred while working with the
database object. If there was an error, the usual behavior is to stop the program and
display the error message reported by the getMessage( ) method.
•  
• Issuing a Query
•  
• The query( ) method on a database object sends SQL to the database:
• $result = $db->query(sql);
•  
• A SQL statement that doesn’t query the database (e.g., INSERT, UPDATE,
DELETE) returns the DB_OK constant to indicate success.
•  
• SQL that performs a query (e.g.,SELECT) returns an object that you can use
to access the results.
• Fetching Results from a Query:
•  
• PEAR DB provides two methods for fetching data from a query result object.
• 1 returns an array corresponding to the next row, and 2stores the row array into a
variable passed as a parameter.
•  Returning the row
•  
• The fetchRow( ) method on a query result returns an array of the next row of results:
•  
• $row = $result->fetchRow([ mode ]);
•  
• This returns either an array of data, NULL if there is no more data, or DB_ERROR if an error
occurred.
•  
• This common idiom uses the fetchRow( ) method to process a result, one row at a time, as
follows:
•  
• while ($row = $result->fetchRow( ))
• {
• if (DB::isError($row)) {
• die($row->getMessage( ));
• }
• Echo $row;}
• Storing the row
•  
• The fetchInto( ) method also gets the next row, but stores it into the array variable
passed as a parameter:
•  
• $success = $result->fetchInto(array, [mode]);
•  
• Like fetchRow( ), fetchInto( ) returns NULL if there is no more data, or DB_ERROR
if an error occurs.
•  
•  
• while ($success = $result->fetchInto($row))
• {
• if (DB::isError($success)) {
• die($success->getMessage( ));
• }
• // do something with the row
• }
• Finishing the result
•  
• A query result object typically holds all the rows returned by the query.
This may consume a lot of memory. To return the memory consumed by
the result of a query to the operating system, use the free () method:
•  
• $result->free( );
• Disconnecting
•  
• To force PHP to disconnect from the database, use the disconnect( )
method on the database object:
• $db->disconnect( );
•  
• This is not strictly necessary, however, as all database connections are
disconnected when the PHP script ends.
•  
• Advanced Database Techniques:
• Placeholders:
•  
• Just as printf( ) builds a string by inserting values into a template, the PEAR
DB can build a query by inserting values into a template.
• Pass the query () function SQL with ?in place of specific values, and add a
second parameter consisting of the array of values to insert into the SQL:
•  
• $result = $db->query(SQL, values);
•  
• For example, this code inserts three entries into the movies
table:
• $movies = array(array('Dr No', 1962),
• array('Goldfinger', 1965),
• array('Thunderball', 1965));
•  
• foreach ($movies as $movie) {
•  
• $db->query('INSERT INTO movies (title,year) VALUES (?,?)',
$movie);
• }
•  
• There are three characters that you can use as placeholder
values in an SQL query:
• ?  A string or number, which will be quoted if necessary
(recommended)
• |  A string or number, which will never be quoted
• & A filename, the contents of which will be included in the
statement (e.g., for storing an image file in a BLOB field)
• Prepare/Execute
•  
• When issuing the same query repeatedly, it can be more
efficient to compile the query once and then execute it
multiple times, using the prepare ( ), execute ( ), and
• executeMultiple ( ) methods
• The first step is to call prepare( ) on the query:
• $compiled = $db->prepare(SQL);
•  
• This returns a compiled query object. The execute( ) method
fills in any placeholders in the query and sends it to the
RDBMS:
•  
• $response = $db->execute(compiled, values);
• The values array contains the values for the placeholders in
the query. The return value is either a query response object,
or DB_ERROR if an error occurred.
• For example, we could insert multiple values into the movies
table like this:
• $movies = array(array('Dr No', 1962),
• array('Goldfinger', 1965),
• array('Thunderball', 1965));
• $compiled = $db->prepare('INSERT INTO movies (title,year)
VALUES (?,?)');
• foreach ($movies as $movie) {
• $db->execute($compiled, $movie);
• }
• The values array must be numerically indexed from 0 and
have values that are arrays of values to insert. The compiled
query is executed once for every entry in values,
• and the query responses are collected in $responses.
•  
• A better way to write the movie-insertions code is:
•  
• $movies = array(array('Dr No', 1962),
• array('Goldfinger', 1965),
• array('Thunderball', 1965));
• $compiled = $q->prepare('INSERT INTO movies (title,year)
VALUES (?,?)');
• $db->executeMultiple($compiled, $movies);
• Shortcuts
•  
• PEAR DB provides a number of methods that perform a query
and fetch the results in one step:
• getOne( ),
• getRow( ),
• getCol( ),
• getAssoc( ),
• getAll( ).
•  
• All of these methods permit placeholders.
• The getOne( ) method fetches the first column of the first row
of data returned by an
•  SQL query:
• $value = $db->getOne(SQL [, values ]);
•  
• For example:
• $when = $db->getOne("SELECT avg(year) FROM movies");
• if (DB::isError($when)) {
• die($when->getMessage( ));
• }
• echo "The average James Bond movie was made in $when";
•  
• The average James Bond movie was made in 1977
• The getRow( ) method returns the first row of data returned
by an SQL query:
•  
• $row = $db->getRow(SQL [, values ]]);
•  
• This is useful if you know only one row will be returned. For
example:
• list($title, $actor) = $db->getRow(
• "SELECT movies.title,actors.name FROM movies,actors
• WHERE movies.year=1977 AND movies.actor=actors.id");
• echo "($title, starring $actor)";
• The getCol( ) method returns a single column from the data
returned by an SQL
• query:
• $col = $db->getCol(SQL [, column [, values ]]);
• The column parameter can be either a number (0, the default,
is the first column), or the column name.
• $titles = $db->getCol("SELECT title FROM movies ORDER BY
year ASC");
• foreach ($titles as $title) {
• echo "$title\n";
• }
• The getAll( ) method returns an array of all the rows returned by
the query:
•  
• $all = $db->getAll(SQL [, values [, fetchmode ]]);
•  
• For example, the following code builds a select box containing the
names of the movies. The ID of the selected movie is submitted as
the parameter value.
• $results = $db->getAll("SELECT id,title FROM movies ORDER BY year
ASC");
• echo "<select name='movie'>\n";
• foreach ($results as $result) {
• echo "<option value={$result[0]}>{$result[1]}</option>\n";
• }
• echo "</select>";
• Four PEAR DB methods provide you with information on a
query result object:
•  
• numRows( ),
• numCols( ),
• affectedRows( ),
• tableInfo( ).
•  
• The numRows( ) and numCols( ) methods tell you the number
of rows and columns returned from a SELECT query:
• $howmany = $response->numRows( );
• $howmany = $response->numCols( );
– The affectedRows( ) method tells you the number of rows affected by
an INSERT,DELETE, or UPDATE operation:
–  
• $howmany = $response->affectedRows( );
• Sequences:
• PEAR DB sequences are an alternative to database-specific ID
assignment (for instance, MySQL’s AUTO_INCREMENT).
• The nextID( ) method returns the next ID for the given
sequence:
• $id = $db->nextID(sequence);
• This example inserts values into the movies table, giving a unique
identifier to each row:
•  
• $movies = array(array('Dr No', 1962),
• array('Goldfinger', 1965),
• array('Thunderball', 1965));
• foreach ($movies as $movie) {
• $id = $db->nextID('movies');
• splice($movie, 0, 0, $id);
• $db->query('INSERT INTO movies (id,title,year) VALUES (?,?,?)',
$movie);
• }
• A sequence is really a table in the database that keeps track of the
last-assigned ID.
•  
• Metadata
•  
• The getListOf( ) method lets you query the database for
information on available databases, users, views, and
functions:
• $data = $db->getListOf(what);
•  
• The what parameter is a string identifying the database
feature to list. Most databases support "databases"; some
support "users", "views", and "functions".
•  
• For example, this stores a list of available databases in $dbs:
• $dbs = $db->getListOf("databases");
•  
• PEAR DB offers the commit ( ) and rollback( ) methods to help
with transactions:
• $res = $db->commit( );
• $res = $db->rollback( );
• If you call commit( ) or rollback( ) on a database that doesn’t
support transactions, the methods return DB_ERROR.

You might also like