SlideShare uma empresa Scribd logo
1 de 29
Introducing
PHP Data Objects
    Wez Furlong
  wez@omniti.com
The Problem
• No consistency of API between DB
  extensions
• Sometimes no self-consistency within
  a given extension
• Duplicated code (but not)
• High maintenance
The PDO solution
• Move PHP specific stuff into one
  extension
• Database specific stuff (only) in their
  own extensions
• Data access abstraction, not
  database abstraction
Features
• Performance
  – Native C code beats a scripted solution
  – Takes advantage of latest PHP 5 internals
• Power
  – Gives you common DB features as a base
  – Still be able to access specialist functions
• Easy
  – Non-intrusive
  – Clear
• Runtime extensible
  – Drivers can be loaded at runtime
Available Drivers
• Oracle OCI             [PDO_OCI]
• ODBC V3, IBM DB2     [PDO_ODBC]
• MySQL 3.x           [PDO_MYSQL]
• Postgres            [PDO_PGSQL]
• SQLite 3.x         [PDO_SQLITE]
• Firebird         [PDO_FIREBIRD]
Getting PDO [unix]
• Build PHP 5
   --with-zlib --prefix=/usr/local/php5
• pear download PDO-alpha
• tar xzf PDO-*.tgz
• cd PDO-*
• PATH=/usr/local/php5/bin:$PATH
• phpize && ./configure && make
• make install
Getting PDO [unix] 2
• Select the driver(s) you need
• pear download PDO_XXX-alpha
• tar xzf PDO_XXX*.tgz
• cd PDO_XXX*
• phpize && ./configure && make
• make install
Getting PDO [win32]
• Grab the DLLs from the snaps site
 http://snaps.php.net/win32/PECL_5_0/
• You need:
  – php_pdo.dll
  – php_pdo_XXX.dll
• Put them in C:php5ext
Switching it on
• Need to enable PDO in your php.ini
• MUST load PDO first
• Unix:
  extension=pdo.so
  extension=pdo_XXX.so
• Windows
  extension=php_pdo.dll
  extension=php_pdo_XXX.dll
Connecting via PDO
try {
  $dbh = new PDO($dsn,
      $user, $password, $options);
} catch (PDOException $e) {
  echo “Failed to connect:”
               . $e->getMessage();
}
DSN format in PDO
• Driver:optional_driver_specific_stuff
  – sqlite:/path/to/db/file
  – sqlite::memory:
  – mysql:host=name;dbname=dbname
  – pgsql:native_pgsql_connection_string
  – oci:dbname=dbname;charset=charset
  – firebird:dbname=dbname;charset=char
    set;role=role
  – odbc:odbc_dsn
DSN Aliasing
• uri:uri
  – Specify location of a file containing actual DSN
    on the first line
  – Works with streams interface, so remote URLs
    can work too
• name          (with no colon)
  –   Maps to pdo.dsn.name in your php.ini
  –   pdo.dsn.name=sqlite:/path/to/name.db
  –   $dbh = new PDO(„name‟);
  –   $dbh = new PDO(„sqlite:/path/to/name.db‟);
• Neither of these allows for user/pass
  (yet!)
Connection management
try {
  $dbh = new PDO($dsn, $user, $pw);
} catch (PDOException $e) {
  echo “connect failed:” . $e->getMessage();
}
// use the database here
// …

// done; release the connection
$dbh = null;
Persistent PDO
$dbh = new PDO($dsn, $user, $pass,
   array(
     PDO_ATTR_PERSISTENT => true
   )
);
• Can specify a string instead of true
  – Useful for keeping 2 connections open
    with similar credentials
Persistent PDO 2
• PDO_ODBC supports native
  connection pooling by default
• Likely to be more resource efficient
  than PDO „pconnect‟
• Can turn it off in php.ini:
  pdo_odbc.connection_pooling=off
• Need to restart web server after
  changing it
Let’s get data
$dbh = new PDO($dsn);
$stmt = $dbh->prepare(
               „SELECT * FROM FOO‟);
$stmt->execute();
while ($row = $stmt->fetch()) {
   print_r($row);
}
Fetch types
• $stmt->fetch(PDO_FETCH_BOTH)
  – Array with numeric and string keys
  – default option
• PDO_FETCH_NUM
  – Array with numeric keys
• PDO_FETCH_ASSOC
  – Array with string keys
• PDO_FETCH_OBJ
  – $obj->name holds the „name‟ column from the row
• PDO_FETCH_BOUND
  – Just returns true until there are no more rows
Let’s change data
$deleted = $dbh->query(
      “DELETE FROM FOO WHERE 1”);

$changes = $dbh->query(
   “UPDATE FOO SET active=1 ”
 . “WHERE NAME LIKE „%joe%‟”);
Smarter Queries
• Quoting is annoying, but essential
• PDO offers a better way
$stmt->prepare(„INSERT INTO CREDITS
  (extension, name) VALUES (:extension,
  :name)‟);
$stmt->execute(array(
  „:extension‟ => „xdebug‟,
  „:name‟ => „Derick Rethans‟
));
Binding for output
$stmt = $dbh->prepare(
          "SELECT extension, name from CREDITS");
if ($stmt->execute()) {
   $stmt->bindColumn(„extension', $extension);
   $stmt->bindColumn(„name',       $name);
   while ($stmt->fetch(PDO_FETCH_BOUND)) {
     echo “Extension: $extensionn”;
     echo “Author: $namen”;
   }
}
Portability Aids
• PDO aims to make it easier to write
  db independent apps
• Number of hacks^Wtweaks for this
  purpose

$dbh->setAttribute(
               PDO_ATTR_ORACLE_NULLS, true);
• Converts empty strings to NULL when fetched
PDO_ATTR_CASE
• Some databases (notably, Oracle) insist on returning
  column names in uppercase

$dbh->setAttribute(PDO_ATTR_CASE, PDO_CASE_UPPER);
$stmt = $dbh->prepare(
         "SELECT extension, name from CREDITS");
if ($stmt->execute()) {
   $stmt->bindColumn(„EXTENSION', $extension);
   $stmt->bindColumn(„NAME',       $name);
   while ($stmt->fetch(PDO_FETCH_BOUND)) {
     echo “Extension: $extensionn”;
     echo “Author: $namen”;
   }
}
Data typing
• Very loose
• uses strings for data
• Gives you more control over data
  conversion
Error handling
• PDO offers 3 different error modes
$dbh->setAttribute(PDO_ATTR_ERRMODE, $mode);
  – PDO_ERRMODE_SILENT
  – PDO_ERRMODE_WARNING
  – PDO_ERRMODE_EXCEPTION
• Attempts to map native codes to
  PDO generic codes
• But still offers native info too
PDO_ERRMODE_SILENT
if (!$dbh->query($sql)) {
   echo $dbh->errorCode() . "<br>";
   $info = $dbh->errorInfo();
   // $info[0] == $dbh->errorCode()
   //    unified error code
   // $info[1] is the driver specific
   //    error code
   // $info[2] is the driver specific
   //    error string
}
PDO_ERRMODE_EXCEPTION
try {
  $dbh->exec($sql);
} catch (PDOException $e) {
  // display warning message print
  $e->getMessage();
  $info = $e->errorInfo;
  // $info[0] == $e->code;
  //    unified error code
  // $info[1] is the driver specific error code
  // $info[2] is the driver specific error string
}
Transactions
try {
  $dbh->beginTransaction();
  $dbh->query(„UPDATE …‟);
  $dbh->query(„UPDATE …‟);
  $dbh->commit();
} catch (PDOException $e) {
  $dbh->rollBack();
}
Cool stuff on the horizon
• Iterators (coming real soon)
  foreach ($stmt->execute() as $row)
• LOB support via streams
  – Bind the parameter
  – fwrite, fread(), fseek() on the LOB
• Scrollable cursors
Resources
• Oracle Technology Network article
 http://www.oracle.com/technology/pub/articles/php_expert
 s/otn_pdo_oracle5.html

• These slides and other PDO news
  bytes
  http://netevil.org
• Bugs?
  http://pecl.php.net/bugs/report.php?
  package=PDO_XXX

Mais conteúdo relacionado

Mais procurados

Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Dan Poltawski
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Fabien Potencier
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Katy Slemon
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)Win Yu
 
Webinar: Replication and Replica Sets
Webinar: Replication and Replica SetsWebinar: Replication and Replica Sets
Webinar: Replication and Replica SetsMongoDB
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 

Mais procurados (20)

Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)
 
Webinar: Replication and Replica Sets
Webinar: Replication and Replica SetsWebinar: Replication and Replica Sets
Webinar: Replication and Replica Sets
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Php functions
Php functionsPhp functions
Php functions
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 

Semelhante a Introducing PHP Data Objects

PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolGordon Forsythe
 
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008phpbarcelona
 
Power shell training
Power shell trainingPower shell training
Power shell trainingDavid Brabant
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011camp_drupal_ua
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Eric Hogue
 

Semelhante a Introducing PHP Data Objects (20)

Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Sa
SaSa
Sa
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Drupal 7 database api
Drupal 7 database api Drupal 7 database api
Drupal 7 database api
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Fatc
FatcFatc
Fatc
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
 
Power shell training
Power shell trainingPower shell training
Power shell training
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 
Building Custom PHP Extensions
Building Custom PHP ExtensionsBuilding Custom PHP Extensions
Building Custom PHP Extensions
 

Mais de webhostingguy

Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Frameworkwebhostingguy
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guidewebhostingguy
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3webhostingguy
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serverswebhostingguy
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidationwebhostingguy
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreementwebhostingguy
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...webhostingguy
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructurewebhostingguy
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.pptwebhostingguy
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandiserswebhostingguy
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Productswebhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mbwebhostingguy
 

Mais de webhostingguy (20)

File Upload
File UploadFile Upload
File Upload
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web servers
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
 
Notes8
Notes8Notes8
Notes8
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandisers
 
OLUG_xen.ppt
OLUG_xen.pptOLUG_xen.ppt
OLUG_xen.ppt
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
 
Reseller's Guide
Reseller's GuideReseller's Guide
Reseller's Guide
 

Introducing PHP Data Objects

  • 1. Introducing PHP Data Objects Wez Furlong wez@omniti.com
  • 2. The Problem • No consistency of API between DB extensions • Sometimes no self-consistency within a given extension • Duplicated code (but not) • High maintenance
  • 3. The PDO solution • Move PHP specific stuff into one extension • Database specific stuff (only) in their own extensions • Data access abstraction, not database abstraction
  • 4. Features • Performance – Native C code beats a scripted solution – Takes advantage of latest PHP 5 internals • Power – Gives you common DB features as a base – Still be able to access specialist functions • Easy – Non-intrusive – Clear • Runtime extensible – Drivers can be loaded at runtime
  • 5. Available Drivers • Oracle OCI [PDO_OCI] • ODBC V3, IBM DB2 [PDO_ODBC] • MySQL 3.x [PDO_MYSQL] • Postgres [PDO_PGSQL] • SQLite 3.x [PDO_SQLITE] • Firebird [PDO_FIREBIRD]
  • 6. Getting PDO [unix] • Build PHP 5 --with-zlib --prefix=/usr/local/php5 • pear download PDO-alpha • tar xzf PDO-*.tgz • cd PDO-* • PATH=/usr/local/php5/bin:$PATH • phpize && ./configure && make • make install
  • 7. Getting PDO [unix] 2 • Select the driver(s) you need • pear download PDO_XXX-alpha • tar xzf PDO_XXX*.tgz • cd PDO_XXX* • phpize && ./configure && make • make install
  • 8. Getting PDO [win32] • Grab the DLLs from the snaps site http://snaps.php.net/win32/PECL_5_0/ • You need: – php_pdo.dll – php_pdo_XXX.dll • Put them in C:php5ext
  • 9. Switching it on • Need to enable PDO in your php.ini • MUST load PDO first • Unix: extension=pdo.so extension=pdo_XXX.so • Windows extension=php_pdo.dll extension=php_pdo_XXX.dll
  • 10. Connecting via PDO try { $dbh = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) { echo “Failed to connect:” . $e->getMessage(); }
  • 11. DSN format in PDO • Driver:optional_driver_specific_stuff – sqlite:/path/to/db/file – sqlite::memory: – mysql:host=name;dbname=dbname – pgsql:native_pgsql_connection_string – oci:dbname=dbname;charset=charset – firebird:dbname=dbname;charset=char set;role=role – odbc:odbc_dsn
  • 12. DSN Aliasing • uri:uri – Specify location of a file containing actual DSN on the first line – Works with streams interface, so remote URLs can work too • name (with no colon) – Maps to pdo.dsn.name in your php.ini – pdo.dsn.name=sqlite:/path/to/name.db – $dbh = new PDO(„name‟); – $dbh = new PDO(„sqlite:/path/to/name.db‟); • Neither of these allows for user/pass (yet!)
  • 13. Connection management try { $dbh = new PDO($dsn, $user, $pw); } catch (PDOException $e) { echo “connect failed:” . $e->getMessage(); } // use the database here // … // done; release the connection $dbh = null;
  • 14. Persistent PDO $dbh = new PDO($dsn, $user, $pass, array( PDO_ATTR_PERSISTENT => true ) ); • Can specify a string instead of true – Useful for keeping 2 connections open with similar credentials
  • 15. Persistent PDO 2 • PDO_ODBC supports native connection pooling by default • Likely to be more resource efficient than PDO „pconnect‟ • Can turn it off in php.ini: pdo_odbc.connection_pooling=off • Need to restart web server after changing it
  • 16. Let’s get data $dbh = new PDO($dsn); $stmt = $dbh->prepare( „SELECT * FROM FOO‟); $stmt->execute(); while ($row = $stmt->fetch()) { print_r($row); }
  • 17. Fetch types • $stmt->fetch(PDO_FETCH_BOTH) – Array with numeric and string keys – default option • PDO_FETCH_NUM – Array with numeric keys • PDO_FETCH_ASSOC – Array with string keys • PDO_FETCH_OBJ – $obj->name holds the „name‟ column from the row • PDO_FETCH_BOUND – Just returns true until there are no more rows
  • 18. Let’s change data $deleted = $dbh->query( “DELETE FROM FOO WHERE 1”); $changes = $dbh->query( “UPDATE FOO SET active=1 ” . “WHERE NAME LIKE „%joe%‟”);
  • 19. Smarter Queries • Quoting is annoying, but essential • PDO offers a better way $stmt->prepare(„INSERT INTO CREDITS (extension, name) VALUES (:extension, :name)‟); $stmt->execute(array( „:extension‟ => „xdebug‟, „:name‟ => „Derick Rethans‟ ));
  • 20. Binding for output $stmt = $dbh->prepare( "SELECT extension, name from CREDITS"); if ($stmt->execute()) { $stmt->bindColumn(„extension', $extension); $stmt->bindColumn(„name', $name); while ($stmt->fetch(PDO_FETCH_BOUND)) { echo “Extension: $extensionn”; echo “Author: $namen”; } }
  • 21. Portability Aids • PDO aims to make it easier to write db independent apps • Number of hacks^Wtweaks for this purpose $dbh->setAttribute( PDO_ATTR_ORACLE_NULLS, true); • Converts empty strings to NULL when fetched
  • 22. PDO_ATTR_CASE • Some databases (notably, Oracle) insist on returning column names in uppercase $dbh->setAttribute(PDO_ATTR_CASE, PDO_CASE_UPPER); $stmt = $dbh->prepare( "SELECT extension, name from CREDITS"); if ($stmt->execute()) { $stmt->bindColumn(„EXTENSION', $extension); $stmt->bindColumn(„NAME', $name); while ($stmt->fetch(PDO_FETCH_BOUND)) { echo “Extension: $extensionn”; echo “Author: $namen”; } }
  • 23. Data typing • Very loose • uses strings for data • Gives you more control over data conversion
  • 24. Error handling • PDO offers 3 different error modes $dbh->setAttribute(PDO_ATTR_ERRMODE, $mode); – PDO_ERRMODE_SILENT – PDO_ERRMODE_WARNING – PDO_ERRMODE_EXCEPTION • Attempts to map native codes to PDO generic codes • But still offers native info too
  • 25. PDO_ERRMODE_SILENT if (!$dbh->query($sql)) { echo $dbh->errorCode() . "<br>"; $info = $dbh->errorInfo(); // $info[0] == $dbh->errorCode() // unified error code // $info[1] is the driver specific // error code // $info[2] is the driver specific // error string }
  • 26. PDO_ERRMODE_EXCEPTION try { $dbh->exec($sql); } catch (PDOException $e) { // display warning message print $e->getMessage(); $info = $e->errorInfo; // $info[0] == $e->code; // unified error code // $info[1] is the driver specific error code // $info[2] is the driver specific error string }
  • 27. Transactions try { $dbh->beginTransaction(); $dbh->query(„UPDATE …‟); $dbh->query(„UPDATE …‟); $dbh->commit(); } catch (PDOException $e) { $dbh->rollBack(); }
  • 28. Cool stuff on the horizon • Iterators (coming real soon) foreach ($stmt->execute() as $row) • LOB support via streams – Bind the parameter – fwrite, fread(), fseek() on the LOB • Scrollable cursors
  • 29. Resources • Oracle Technology Network article http://www.oracle.com/technology/pub/articles/php_expert s/otn_pdo_oracle5.html • These slides and other PDO news bytes http://netevil.org • Bugs? http://pecl.php.net/bugs/report.php? package=PDO_XXX