0% found this document useful (0 votes)
169 views

Zend DB

The document discusses the Zend DB component which provides classes for connecting to databases and executing queries. It describes the main classes like Zend_Db_Adapter for connecting to databases, Zend_Db_Select for building SQL queries, and Zend_Db_Statement for executing prepared statements. Methods are shown for connecting to databases, building queries using clauses like FROM and JOIN, fetching results, and profiling queries for optimization.

Uploaded by

Nithin Surendran
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views

Zend DB

The document discusses the Zend DB component which provides classes for connecting to databases and executing queries. It describes the main classes like Zend_Db_Adapter for connecting to databases, Zend_Db_Select for building SQL queries, and Zend_Db_Statement for executing prepared statements. Methods are shown for connecting to databases, building queries using clauses like FROM and JOIN, fetching results, and profiling queries for optimization.

Uploaded by

Nithin Surendran
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

ZEND DB

CONTENTS Zend_Db_Adapter Zend_Db_Statement Zend_Db_Profiler Zend_Db_Select Zend_Db_Table Zend_Db_Table_Row Zend_Db_Table_Rowset Zend_Db_Table Relationships Zend_Db_Table_Definition

ZEND_DB_ADAPTER

ZEND_DB_ADAPTER

basic class you use to connect your PHP application to an RDBMS


IBM DB2 and Informix Dynamic Server (IDS), using the pdo_ibm PHP extension MariaDB, using the pdo_mysql PHP extension MySQL, using the pdo_mysql PHP extension Microsoft SQL Server, using the pdo_dblib PHP extension Oracle, using the pdo_oci PHP extension PostgreSQL, using the pdo_pgsql PHP extension SQLite, using the pdo_sqlite PHP extension

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Using a Zend_Db Adapter Constructor


$db = new Zend_Db_Adapter_Pdo_Mysql(array( 'host' => '127.0.0.1', 'username' => 'webuser', 'password' => 'xxxxxxxx', 'dbname' => 'test' ));

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Using the Zend_Db Factory


$db = Zend_Db::factory('Pdo_Mysql', array( 'host' => '127.0.0.1', 'username' => 'webuser', 'password' => 'xxxxxxxx', 'dbname' => 'test' ));

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Using Zend_Config with the Zend_Db Factory


$config = new Zend_Config( array( 'database' => array( 'adapter' => 'Mysqli', 'params' => array( 'host' => '127.0.0.1', 'dbname' => 'test', 'username' => 'webuser', 'password' => 'secret', ) ) ) )$db = Zend_Db::factory($config->database) Can use Zend_Config_Ini and Zend_Config_Xml. Instead of Zend_Config

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Using Zend_Config with the Zend_Db Factory


$config = new Zend_Config( array( 'database' => array( 'adapter' => 'Mysqli', 'params' => array( 'host' => '127.0.0.1', 'dbname' => 'test', 'username' => 'webuser', 'password' => 'secret', ) ) ) )$db = Zend_Db::factory($config->database) Can use Zend_Config_Ini and Zend_Config_Xml. Instead of Zend_Config

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Adapter Parameters

Host: Username: Password: Dbname: port Charset: options: this parameter is an associative array of options

that are generic to all Zend_Db_Adapter classes. driver_options: this parameter is an associative array of additional options that are specific to a given database extension. One typical use of this parameter is to set attributes of a PDO driver. adapterNamespace: names the initial part of the class name for the adapter, instead of 'Zend_Db_Adapter'. Use this if you need to use the factory() method to load a non-Zend database adapter class.

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Adapter Parameters

Host: Username: Password: Dbname: port Charset: options: this parameter is an associative array of options

that are generic to all Zend_Db_Adapter classes. driver_options: this parameter is an associative array of additional options that are specific to a given database extension. One typical use of this parameter is to set attributes of a PDO driver. adapterNamespace: names the initial part of the class name for the adapter, instead of 'Zend_Db_Adapter'. Use this if you need to use the factory() method to load a non-Zend database adapter class.

ZEND_DB_ADAPTER

Connecting to a Database Using an Adapter

Adapter options

Case-Folding $options = array( Zend_Db::CASE_FOLDING => Zend_Db::CASE_UPPER ); Auto-Quoting $options = array( Zend_Db::AUTO_QUOTE_IDENTIFIERS => false ); Serialization $options = array( Zend_Db::ALLOW_SERIALIZATION => false );

Dbname: port Charset: options: this parameter is an associative array of options that are generic to all

Zend_Db_Adapter classes. driver_options: this parameter is an associative array of additional options that are specific to a given database extension. One typical use of this parameter is to set attributes of a PDO driver. adapterNamespace: names the initial part of the class name for the adapter, instead of 'Zend_Db_Adapter'. Use this if you need to use the factory() method to load a non-Zend database adapter class.

ZEND_DB_ADAPTER
Reading Query Results Fetching a Complete Result Set

$sql = 'SELECT * FROM bugs WHERE bug_id = ?'; $result = $db->fetchAll($sql, 2);

The first argument


string containing a SELECT statement. an object of class Zend_Db_Select. ( Adapter automatically converts this object to a string representation of the SELECT statement).

The second argument

is an array of values to substitute for parameter placeholders in the SQL statement.

ZEND_DB_ADAPTER

Reading Query Results

Changing the Fetch Mode

Fetch all selects array or rows as associate array can change using the setFetchMode() method. $db->setFetchMode(Zend_Db::FETCH_OBJ);
$result = $db->fetchAll('SELECT * FROM bugs WHERE bug_id = ?', 2);

// $result is an array of objects


echo $result[0]->bug_description;

ZEND_DB_ADAPTER

Reading Query Results

Fetch Modes

Zend_Db::FETCH_ASSOC: return data in an array of


associative arrays.

Zend_Db::FETCH_NUM: return data in an array of arrays.


The arrays are indexed by integers

Zend_Db::FETCH_BOTH: return data in an array of arrays. Zend_Db::FETCH_COLUMN: return data in an array of

values. The value in each array is the value returned by one column of the result set. By default, this is the first column, indexed by 0. Zend_Db::FETCH_OBJ: return data in an array of objects

ZEND_DB_ADAPTER

Reading Query Results

Fetch functions
fetchAssoc() fetchCol() fetchPairs() fetchRow() fetchOne()

ZEND_DB_ADAPTER

Reading Query Results

Other functions

insert(table) lastInsertId() update(table name, name,associtedarray(field,val), delete(table, condition') quote() quoteInto \ $sql = $db->quoteInto("SELECT * FROM bugs WHERE reported_by = ?", "O'Reilly quoteIdentifier() Quote tablename beginTransaction() commit() rollBack() closeConnection();

ZEND_DB_STATEMENT

ZEND_DB_STATEMENT
Creating sql statement based on the PDOStatement object in the PHP Data Objects

ZEND_DB_STATEMENT

Creating sql statement


$stmt = $db->query( 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?', array('goofy', 'FIXED') ); $stmt->execute(array('goofy', 'FIXED'));
Or $sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?'; $stmt = new Zend_Db_Statement_Mysqli($db, $sql); $stmt->execute(array('goofy', 'FIXED'));

ZEND_DB_STATEMENT

Fetching from sql statement


Using fetch(), fetchall(), fetchcolumn(), fetchObject()
$stmt = $db->query('SELECT * FROM bugs'); while ($row = $stmt->fetch()) { echo $row['bug_description']; }

ZEND_DB_PROFILER

ZEND_DB_PROFILER
can be enabled to allow profiling of queries Profiling includes elapsed time, inspection of queries etc

db.profiler.class = "MyProject_Db_Profiler" db.profiler.enabled = true

ZEND_DB_PROFILER

Using profiler

Getting profiler object using getProfiler() method Functions availble


getTotalNumQueries() getTotalElapsedSecs() getQueryProfiles() getLastQueryProfile() returns the last (most recent) query profile, regardless of whether or not the query has finished (if it hasn't, the end time will be NULL) clear() getQuery() returns the SQL text of the query getQueryParams() getElapsedSecs() returns the number of seconds the query ran.

ZEND_DB_PROFILER

Advanced Profiler Usage

Filter by query elapsed time


$profiler->setFilterElapsedSecs(5); $profiler->setFilterElapsedSecs(null);

Filter by query type


setFilterQueryType() Like insert,delete,update,etc

$profiler->setFilterQueryType(Zend_Db_Profiler::SELECT | Zend_Db_Profiler::INSERT | Zend_Db_Profiler::UPDATE);

Profiling with Firebug

Zend_Db_Profiler_Firebug sends profiling infomation to the Firebug Console.

ZEND_DB_SELECT

ZEND_DB_SELECT
represents a SQL SELECT query statement. Features

Object-oriented methods for specifying SQL queries in a piece-by-piece manner; Database-independent abstraction of some parts of the SQL query; Automatic quoting of metadata identifiers in most cases, to support identifiers containing SQL reserved words and special characters; Quoting identifiers and values, to help reduce risk of SQL injection attack

ZEND_DB_SELECT

Creating a Select Object

$select = $db->select(); or $select = new Zend_Db_Select($db); where $db is database adaptor

Building Select queries


// Add a FROM clause

// Create the Zend_Db_Select object


$select = $db->select(); $select->from( ...specify table and columns... )

// Add a WHERE clause

$select->where( ...specify search criteria... )

// Add an ORDER BY clause

$select->order( ...specify sorting criteria... )

ZEND_DB_SELECT

Example
SELECT p."product_id", p."product_name", d.* FROM "products" AS p JOIN "product_description" AS d ON p.product_id = d.product_id

$select = $db->select() ->from(array('p' => 'products'), array('product_id', 'product_name')) ->join(array(d' => product_description'), 'p.product_id = d.product_id');

ZEND_DB_SELECT

Clauses available

FROM clause
$select->from(table names , fields , shema ); Table name can be associate array Array(p=>products) produce from products as p Fields name can be array too

Array('prodno' => 'product_id', 'product_name')


produce
Select p. product_id as prodno , p.product_name

Can use Zend_Db_Expr if we need expression in the fields . Fields in ( ) implicitly treated as Zend_Db_Expr Can use $db->quoteIdentifier(identifier') if some identifier are using in fields or expression

ZEND_DB_SELECT

Clauses available

JOIN clause

Other join functions


$select->join(table name,join condition,list of columns ); Table name -> associate array for table names Join coditon -> eg p.product_id = l.product_id List of columns -> associate array of fields selected from this table Usualy represents a inner join LEFT JOIN with the joinLeft() RIGHT JOIN with the joinRight() FULL JOIN with the joinFull() CROSS JOIN with the joinCross() * no conditon needed for cross join NATURAL JOIN with the joinNatural() * no conditon needed for natural join

ZEND_DB_SELECT

Clauses available

WHERE Clause

$select-> where(conditon) Can use parameters with where

eg where(product_id=?,10) Eg where ( product_id IN (?),array(10,11,12)) $select-> where(conditon 1) $select-> where(conditon 2) // usually adds by AND $select-> where(conditon 1) $select-> where(conditon 2) $select-> orWhere(conditon 3) // condion 1 and

Can use array of parameters

Multiple where can be used


For or condtion use orWhere()


conditon2 or conditon 3

ZEND_DB_SELECT

Clauses available

Other Clauses
GROUP BY Clause $select-> group('p.product_id'); HAVING Clause Restricting groups $select->having('items_per_product > 10'); ORDER BY Clause $select->order(array(field1 DESC',field 2')); LIMIT Clause $select-> limit(20, 10);

The first argument to this method is the desired count of rows. The second argument is the number of rows to skip.

ZEND_DB_SELECT

Clauses available

Other functions
DISTINCT Query Modifier $select ->distinct(); Add distint keyword FOR UPDATE Query Modifier $select ->forUpdate (); Add FOR UPDATE keyword UNION Query Combining 2 statement using union

$select ->union(array($sql1, $sql2))

ZEND_DB_SELECT

Clauses available

Other functions

getPart() Getting part of a query

$orderData = $select->getPart( 'order' );

reset() Clears all parts of the query

$select->reset(); $select->reset( Zend_Db_Select::ORDER ); //only clears order

Clears a perticular part

__toString(); Get string equllent of query

ZEND_DB_TABLE

ZEND_DB_TABLE
object-oriented interface to database tables provides methods for many common operations on tables base class is extensible ,can add custom logic Can use object of Zend_Db_Table or define a table class

Using Zend_Db_Table
Zend_Db_Table::setDefaultAdapter($dbAdapter); $bugTable = new Zend_Db_Table(table name');

ZEND_DB_TABLE

Defining a Table Class

extends Zend_Db_Table_Abstract. use the protected variable $_name for tabel name Other optional variables of the class
$_schema - schema name $_primary - primary key If not provided tries to find it by using describe table $_rowClass - row class Default Zend_Db_Table_Row $_rowsetClass - Row set class Default Zend_Db_Table_Rowset $_referenceMap - adding references $_dependentTables array of dependend tables $_sequence - to inform classs we are using auto increment key default will be true

ZEND_DB_TABLE

Functions Available
info($key = null) - Returns table information. Select() - Returns an instance of a Zend_Db_Table_Select object. insert($data_array) - Inserts a new row. isIdentity($column) - Check if the provided column is an identity of the table update($data_array , $where) - Updates existing rows. delete($where) - Deletes existing rows.

ZEND_DB_TABLE

Functions Available

find() - Fetches rows by primary key. The argument specifies one or more primary key value(s). To find multiple rows by primary key, the argument must be an array. fetchAll($where, $order, $count, $offset) - Fetches all rows object of Zend_Db_Table_Rowset. Parameters are defaulted to null if not provided fetchRow($where, $order, $offset) - Fetches one row in an object of type Zend_Db_Table_Row_Abstract, fetchNew(), createRow() - Fetches a new blank row (not from the database).

ZEND_DB_TABLE_ROW

ZEND_DB_TABLE_ROW

contains an individual row of a Zend_Db_Table object

Rows can be Fetched,Saved,deleted from database Fetched using


a fetchRow(), fetchAll() ->current(); $row->save(); Saves current row to save ,If the row is created using fetchnew() or createRow() then a new row is inserted other wise its updated $row->delete(); Current row is deleted

Writed or saved using

Deleted using

ZEND_DB_TABLE_ROW

contains an individual row of a Zend_Db_Table object

Rows can be Fetched,Saved,deleted from database Fetched using


a fetchRow(), fetchAll() ->current(); $row->save(); Saves current row to save ,If the row is created using fetchnew() or createRow() then a new row is inserted other wise its updated $row->delete(); Current row is deleted

Writed or saved using

Deleted using

You might also like