SlideShare a Scribd company logo
PHP Data Objects

    Wez Furlong
    Lead Architect
 <wez@omniti.com>
we're hiring: 
                  http://omniti.com/people/jobs



              About the author
•   PHP Core Developer since 2001
•   Author of the Streams layer
•   “King” of PECL
•   Author of most of PDO and its drivers
•   Day‐job is developing the Fastest MTA on 
    Earth
we're hiring: 
                  http://omniti.com/people/jobs



                Coming up…
•   Problems with PHP DB access
•   PDO Solution
•   Features / Drivers
•   Installation
•   Getting Started
•   Features
we're hiring: 
                 http://omniti.com/people/jobs



               The Problem
• No consistency of API between DB extensions
• Sometimes no self‐consistency within a given 
  extension
• Duplicated code (but not)
• High maintenance
we're hiring: 
                 http://omniti.com/people/jobs



            The PDO Solution
• Move PHP specific stuff into one extension
• Database specific stuff (only) in their own 
  extensions
• Data access abstraction, not database 
  abstraction
we're hiring: 
                 http://omniti.com/people/jobs



                   Features
Performance
• Native C code beats a scripted solution
• Takes advantage of latest PHP 5 internals
we're hiring: 
                  http://omniti.com/people/jobs



                    Features
Power
• Gives you common DB features as a base
• Still be able to access specialist functions
we're hiring: 
                   http://omniti.com/people/jobs



               What can it do?
•   Prepare/execute, bound parameters
•   Transactions
•   LOBS
•   Scrollable Cursors
•   SQLSTATE error codes, flexible error handling
•   Portability attributes
we're hiring: 
                   http://omniti.com/people/jobs



              Available Drivers
•   Pretty much all of them:
•   MySQL, PostgreSQL
•   ODBC, DB2, OCI
•   SQLite (2 and 3)
•   Sybase/FreeTDS/MSSQL
•   Firebird (needs love)
we're hiring: 
                http://omniti.com/people/jobs



                 Installing
• Ships with PHP 5.1
• Available for PHP 5.0.x via PECL
• DLLs downloadable for both on Windows via 
  http://pecl4win.php.net
we're hiring: 
              http://omniti.com/people/jobs



        Building w/ PHP 5.0
./configure 
       ‐‐with‐zlib 
       ‐‐prefix=/usr/local/php5
• pear upgrade pear
• pear install PDO
• extension=pdo.so in your php.ini
we're hiring: 
              http://omniti.com/people/jobs



         Building w/ PHP 5.0
• Select the driver(s) you need
• pear install PDO_XXX
• extension=pdo_xxx.so in your php.ini
we're hiring: 
                 http://omniti.com/people/jobs



           Installing on Win32
• Grab the DLLs from the snaps site 
  http://pecl4win.php.net/
• You need:
  – php_pdo.dll
  – php_pdo_XXX.dll
• Put them in C:php5ext
we're hiring: 
                http://omniti.com/people/jobs



             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
we're hiring: 
            http://omniti.com/people/jobs



       Connecting via PDO
try {
  $dbh = new PDO($dsn, $user,
          $password, $options);
} catch (PDOException $e) {
  echo ”Failed to connect:”
          . $e‐>getMessage();
}
we're hiring: 
                  http://omniti.com/people/jobs



                         DSNs
• In general
  drivername:<driver‐specific‐stuff>
we're hiring: 
                http://omniti.com/people/jobs



                       DSNs
• mysql:host=name;dbname=dbname
• pgsql:native_pgsql_connection_string

• odbc:odbc_dsn
• oci:dbname=dbname;charset=charset
we're hiring: 
                  http://omniti.com/people/jobs



                         DSNs
• sqlite:/path/to/db/file
• sqlite::memory:

• sqlite2:/path/to/sqlite2/file
• sqlite2::memory:
we're hiring: 
                    http://omniti.com/people/jobs



                  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
we're hiring: 
                 http://omniti.com/people/jobs



               DSN Aliasing
• pdo.dsn.name=sqlite:/path/to/name.db

$dbh = new PDO(quot;namequot;);

Same as:
$dbh = new PDO(quot;sqlite:/path/to/name.dbquot;);
we're hiring: 
              http://omniti.com/people/jobs



     Connection Management
try {
  $dbh = new PDO($dsn, $user, $pw);
  // use the database here
  // ...
  // done; release the connection
  $dbh = null;
} catch (PDOException $e) {
  echo ”connect failed:”
         . $e‐>getMessage();
}
we're hiring: 
                http://omniti.com/people/jobs



             Persistent PDO
• Connection stays alive between requests

$dbh = new PDO($dsn, $user, $pass,
 array(
  PDO::ATTR_PERSISTENT => true
 )
);
we're hiring: 
                   http://omniti.com/people/jobs



               Persistent PDO
• Can specify your own cache key

$dbh = new PDO($dsn, $user, $pass,
 array(
  PDO::ATTR_PERSISTENT => “my‐key”
 )
);
• Useful for keeping separate persistent connections
we're hiring: 
                   http://omniti.com/people/jobs



               Persistent PDO
• The ODBC driver runs with connection pooling 
  enabled by default
• “better” than PHP‐level persistence
  – Pool is shared at the process level
• Can be forced off by setting
  – pdo_odbc.connection_pooling=off
we're hiring: 
              http://omniti.com/people/jobs



            Let’s get data
$dbh = new PDO($dsn);
$stmt = $dbh‐>prepare(
                quot;SELECT * FROM FOOquot;);
$stmt‐>execute();
while ($row = $stmt‐>fetch()) {
    print_r($row);
}
$stmt = null;
we're hiring: 
                http://omniti.com/people/jobs



         Forward‐only cursors
• Also known as quot;unbufferedquot; queries in mysql 
  parlance
• They are the default cursor type
• rowCount() doesn't have meaning
• FAST!
we're hiring: 
                 http://omniti.com/people/jobs



         Forward‐only cursors
• Other queries are likely to block
• You must fetch all remaining data before 
  launching another query
• $stmt‐>closeCursor()
we're hiring: 
              http://omniti.com/people/jobs



          Buffered Queries
$dbh = new PDO($dsn);
$stmt = $dbh‐>query(
                quot;SELECT * FROM FOOquot;);
$rows = $stmt‐>fetchAll();
$count = count($rows);
foreach ($rows as $row) {
    print_r($row);
}
$stmt = null;
we're hiring: 
                       http://omniti.com/people/jobs



                   Data typing
•   Very loose
•   uses strings for data
•   Gives you more control over data conversion
•   Supports integers where 1:1 mapping exists
•   Is float agnostic
    – PDO is precise
we're hiring: 
                   http://omniti.com/people/jobs



                  Fetch modes
• $stmt‐>fetch(PDO::FETCH_BOTH)
  – Array with numeric and string keys
  – default option
• PDO::FETCH_NUM
  – Numeric only
• PDO::FETCH_ASSOC
  – String only
we're hiring: 
                  http://omniti.com/people/jobs



                Fetch modes
• PDO::FETCH_OBJ
  – stdClass object
  – $obj‐>name == ‘name’ column
• PDO::FETCH_CLASS
  – You choose the class
• PDO::FETCH_INTO
  – You provide the object
we're hiring: 
                   http://omniti.com/people/jobs



                 Fetch modes
• PDO::FETCH_COLUMN
  – Fetches only a particular column
• PDO::FETCH_BOUND
  – Only fetches into bound variables
• PDO::FETCH_FUNC
  – Returns the result of a callback
• and more…
we're hiring: 
               http://omniti.com/people/jobs



                 Iterators
$dbh = new PDO($dsn);
$stmt = $dbh‐>query(
              quot;SELECT name FROM FOOquot;,
              PDO::FETCH_COLUMN, 0);
foreach ($stmt as $name) {
     echo quot;Name: $namenquot;;
}
$stmt = null;
we're hiring: 
            http://omniti.com/people/jobs



          Changing data
$deleted = $dbh‐>exec(
    quot;DELETE FROM FOO WHERE 1quot;);

$changes = $dbh‐>exec(
    quot;UPDATE FOO SET active=1 quot;
  . quot;WHERE NAME LIKE '%joe%'quot;);
we're hiring: 
                     http://omniti.com/people/jobs



         Autonumber/sequences
$dbh‐>exec(
     quot;insert into foo values (...)quot;);
echo $dbh‐>lastInsertId();

$dbh‐>exec(
     quot;insert into foo values (...)quot;);
echo $dbh‐>lastInsertId(“seqname”);

It’s up to you to call it appropriately
we're hiring: 
                      http://omniti.com/people/jobs



                 Smarter queries
• Quoting is annoying, but essential
• PDO offers a better way

$stmt = $db‐>prepare(“INSERT INTO CREDITS ”
           .“(extension, name) ”
           .“VALUES (:extension, :name)”);
$stmt‐>execute(array(
    'extension' => 'xdebug',
    'name'      => 'Derick Rethans'
));
we're hiring: 
                      http://omniti.com/people/jobs



                 Smarter queries
• Quoting is annoying, but essential
• PDO offers a better way

$stmt = $db‐>prepare(“INSERT INTO CREDITS ”
          .“(extension, name) ”
          .“VALUES (?, ?)”);
$stmt‐>execute(array(
                  'xdebug',
                  'Derick Rethans'
));
we're hiring: 
                 http://omniti.com/people/jobs



               $db‐>quote()
• If you still need to quote things “by‐hand”
• Currently a no‐op for the ODBC driver
we're hiring: 
              http://omniti.com/people/jobs



         Stored Procedures
$stmt = $dbh‐>prepare(
            quot;CALL sp_set_string(?)quot;);
$stmt‐>bindParam(1, $str);
$str = ‘foo’;
$stmt‐>execute();
we're hiring: 
              http://omniti.com/people/jobs



          OUT parameters
$stmt = $dbh‐>prepare(
            quot;CALL sp_get_string(?)quot;);
$stmt‐>bindParam(1, $ret,
               PDO::PARAM_STR, 4000);
if ($stmt‐>execute()) {
     echo quot;Got $retnquot;;
}
we're hiring: 
                 http://omniti.com/people/jobs



          IN/OUT parameters
$stmt = $dbh‐>prepare(
                quot;call @sp_inout(?)quot;);
$val = quot;My Input Dataquot;;
$stmt‐>bindParam(1, $val,
                 PDO::PARAM_STR|
                 PDO::PARAM_INPUT_OUTPUT,
                 4000);
if ($stmt‐>execute()) {
    echo quot;Got $valnquot;;
}
we're hiring: 
                 http://omniti.com/people/jobs



     Binding columns for output
$stmt = $dbh‐>prepare(
      quot;SELECT extension, name from CREDITSquot;);
if ($stmt‐>execute()) {
  $stmt‐>bindColumn('extension', $extension);
  $stmt‐>bindColumn('name',      $name);
  while ($stmt‐>fetch(PDO::FETCH_BOUND)) {
     echo quot;Extension: $extensionnquot;;
     echo quot;Author: $namenquot;;
  }
}
we're hiring: 
               http://omniti.com/people/jobs



            Portability Aids
• PDO aims to make it easier to write db 
  independent apps
• Number of hacks^Wtweaks for this purpose
we're hiring: 
                    http://omniti.com/people/jobs



             Oracle style NULLs
• Oracle translates empty strings into NULLs
• $dbh‐>setAttribute(PDO::ATTR_ORACLE_NULLS, true);

• Translates empty strings into NULLs when 
  fetching data
• But won’t change them on insert
we're hiring: 
                http://omniti.com/people/jobs



               Case folding
• The ANSI SQL standard says that column 
  names are returned in upper case
• High end databases (eg: Oracle and DB2) 
  respect this
• Most others don’t
$dbh‐>setAttribute(  
  PDO::ATTR_CASE,
  PDO::CASE_UPPER);
we're hiring: 
                http://omniti.com/people/jobs



             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 SQLSTATE 
  standard codes
• But still offers native info too
we're hiring: 
              http://omniti.com/people/jobs



      PDO::ERRMODE_SILENT
if (!$dbh‐>query($sql)) {
   echo $dbh‐>errorCode() . quot;<br>quot;;
   $info = $dbh‐>errorInfo();
   // $info[0] == $dbh‐>errorCode()
   //     SQLSTATE error code
   // $info[1] is the driver specific
   //     error code
   // $info[2] is the driver specific
   //     error string
}
we're hiring: 
                 http://omniti.com/people/jobs



     PDO::ERRMODE_WARNING
• Same as PDO::ERRMODE_SILENT
• But, raises an E_WARNING as errors are 
  detected
• You can selectively suppress the warnings 
  with @ operator
we're hiring: 
                    http://omniti.com/people/jobs



     PDO_ERRMODE_EXCEPTION
try {
   $dbh‐>exec($sql);
} catch (PDOException $e) {
   // display warning message print
   $e‐>getMessage();
   $info = $e‐>errorInfo;
   // $info[0] == $e‐>code;
   //     SQLSTATE error code
   // $info[1] is the driver specific error code
   // $info[2] is the driver specific error string
}
we're hiring: 
            http://omniti.com/people/jobs



           Transactions
$dbh‐>beginTransaction();
try {
   $dbh‐>query(quot;UPDATE ...quot;);
   $dbh‐>query(quot;UPDATE ...quot;);
   $dbh‐>commit();
} catch (Exception $e) {
   $dbh‐>rollBack();
}
we're hiring: 
                 http://omniti.com/people/jobs



            LOBs via Streams
• Large objects are usually 4kb or more in size
• Advantageous to avoid fetching them until 
  you really need to
• Mature RDBMS offer LOB APIs for this
• PDO exposes LOBS as Streams
we're hiring: 
                 http://omniti.com/people/jobs



           Fetching an image
$db = new PDO($dsn);
$stmt = $db‐>prepare(
     “select contenttype, imagedata”
    .“ from images where id=?”);
$stmt‐>execute(array($_GET['id']));
$stmt‐>bindColumn(1, $type, PDO::PARAM_STR, 
  256);
$stmt‐>bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt‐>fetch(PDO::FETCH_BOUND);
header(quot;Content‐Type: $typequot;);
fpassthru($lob);
we're hiring: 
                 http://omniti.com/people/jobs



           Inserting an image
$db = new PDO($dsn);
$stmt = $db‐>prepare(
            “insert into images ”
           .“(id, contenttype, imagedata) ”
           .“values (?, ?, ?)”);
$id = get_new_id();
$fp = fopen($_FILES['file']['tmp_name'],
            'rb');
$stmt‐>bindParam(1, $id);
$stmt‐>bindParam(2,$_FILES['file']['type']);
$stmt‐>bindParam(3, $fp, PDO::PARAM_LOB);
$stmt‐>execute();
we're hiring: 
                 http://omniti.com/people/jobs



            Scrollable Cursors
• Allow random access to a rowset
• Higher resource usage than forward‐only 
  cursors
• Can be used to emulate limit, offset style 
  paged queries
• Can be used for positioned updates (more 
  useful for CLI/GUI apps)
we're hiring: 
                http://omniti.com/people/jobs



          Positioned updates
• An open (scrollable) cursor can be used to 
  target a row for another query
• Name your cursor by setting 
  PDO::ATTR_CURSOR_NAME during prepare()
• UPDATE foo set bar = ? WHERE 
  CURRENT OF cursor_name
we're hiring: 
             http://omniti.com/people/jobs



       Multi‐rowset queries
$stmt = $dbh‐>query(
      quot;call sp_multi_results()quot;);
do {
  while($row = $stmt‐>fetch()) {
     print_r($row);
  }
} while ($stmt‐>nextRowset());
we're hiring: 
                           http://omniti.com/people/jobs



                         Questions?
• These slides:
   – http://omniti.com/resources/talks
• Gold:
   – http://troels.arvin.dk/db/rdbms/#select‐limit‐offset
• Publications
   – google for “wez furlong pdo db2”
   – google for “wez furlong pdo oci”
• My blog: http://netevil.org
• We’re hiring: we have positions open for
   – PHP, Perl and C developers
   – a security analyst
   – http://omniti.com/people/jobs

More Related Content

What's hot

Ruby HTTP clients
Ruby HTTP clientsRuby HTTP clients
Ruby HTTP clients
Zoran Majstorovic
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
Jason Davies
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
dreamwidth
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet CampPuppet
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
sickill
 
Scalable talk notes
Scalable talk notesScalable talk notes
Scalable talk notes
Perrin Harkins
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
Fabio Tiriticco
 
Php assíncrono com_react_php
Php assíncrono com_react_phpPhp assíncrono com_react_php
Php assíncrono com_react_php
Renato Lucena
 
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Alexander Lisachenko
 
Introduction to performance tuning perl web applications
Introduction to performance tuning perl web applicationsIntroduction to performance tuning perl web applications
Introduction to performance tuning perl web applications
Perrin Harkins
 
Building Scalable Websites with Perl
Building Scalable Websites with PerlBuilding Scalable Websites with Perl
Building Scalable Websites with Perl
Perrin Harkins
 
Turbogears Presentation
Turbogears PresentationTurbogears Presentation
Turbogears Presentation
didip
 
Developing OpenResty Framework
Developing OpenResty FrameworkDeveloping OpenResty Framework
Developing OpenResty FrameworkAapo Talvensaari
 
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsIntroducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applications
John Hann
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with Rack
DonSchado
 
Ruby on Rails Security
Ruby on Rails SecurityRuby on Rails Security
Ruby on Rails Securityamiable_indian
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
Ronald Huereca
 
Plongée dans l'écosystème Laravel
Plongée dans l'écosystème LaravelPlongée dans l'écosystème Laravel
Plongée dans l'écosystème Laravel
Gabriel Pillet 🐙
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
Pance Cavkovski
 
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
Viktor Todorov
 

What's hot (20)

Ruby HTTP clients
Ruby HTTP clientsRuby HTTP clients
Ruby HTTP clients
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Scalable talk notes
Scalable talk notesScalable talk notes
Scalable talk notes
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
Php assíncrono com_react_php
Php assíncrono com_react_phpPhp assíncrono com_react_php
Php assíncrono com_react_php
 
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
 
Introduction to performance tuning perl web applications
Introduction to performance tuning perl web applicationsIntroduction to performance tuning perl web applications
Introduction to performance tuning perl web applications
 
Building Scalable Websites with Perl
Building Scalable Websites with PerlBuilding Scalable Websites with Perl
Building Scalable Websites with Perl
 
Turbogears Presentation
Turbogears PresentationTurbogears Presentation
Turbogears Presentation
 
Developing OpenResty Framework
Developing OpenResty FrameworkDeveloping OpenResty Framework
Developing OpenResty Framework
 
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsIntroducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applications
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with Rack
 
Ruby on Rails Security
Ruby on Rails SecurityRuby on Rails Security
Ruby on Rails Security
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
Plongée dans l'écosystème Laravel
Plongée dans l'écosystème LaravelPlongée dans l'écosystème Laravel
Plongée dans l'écosystème Laravel
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
 

Similar to Os Furlong

Capistrano2
Capistrano2Capistrano2
Capistrano2
Luca Mearelli
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB app
Lenz Gschwendtner
 
Api Design
Api DesignApi Design
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
ZendCon
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
Rob Knight
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
SearchMonkey
SearchMonkeySearchMonkey
SearchMonkey
Paul Tarjan
 
Gofer 200707
Gofer 200707Gofer 200707
Gofer 200707oscon2007
 
Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
Dave Ross
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
jeresig
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
dosire
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
Sam Keen
 
Streamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web FrameworksStreamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web Frameworks
guestf7bc30
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
Jesse Vincent
 
Revoke-Obfuscation
Revoke-ObfuscationRevoke-Obfuscation
Revoke-Obfuscation
Daniel Bohannon
 
第1回PHP拡張勉強会
第1回PHP拡張勉強会第1回PHP拡張勉強会
第1回PHP拡張勉強会
Ippei Ogiwara
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
Hi-Tech College
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
Elizabeth Smith
 

Similar to Os Furlong (20)

Capistrano2
Capistrano2Capistrano2
Capistrano2
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB app
 
Api Design
Api DesignApi Design
Api Design
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
SearchMonkey
SearchMonkeySearchMonkey
SearchMonkey
 
Gofer 200707
Gofer 200707Gofer 200707
Gofer 200707
 
Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
Streamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web FrameworksStreamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web Frameworks
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
 
Revoke-Obfuscation
Revoke-ObfuscationRevoke-Obfuscation
Revoke-Obfuscation
 
第1回PHP拡張勉強会
第1回PHP拡張勉強会第1回PHP拡張勉強会
第1回PHP拡張勉強会
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 

More from oscon2007

J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Touroscon2007
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5oscon2007
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifmoscon2007
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Moleoscon2007
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashearsoscon2007
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swposcon2007
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Mythsoscon2007
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholisticoscon2007
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillipsoscon2007
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdatedoscon2007
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reformoscon2007
 
Railsconf2007
Railsconf2007Railsconf2007
Railsconf2007oscon2007
 
Oscon Mitchellbaker
Oscon MitchellbakerOscon Mitchellbaker
Oscon Mitchellbakeroscon2007
 

More from oscon2007 (20)

J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Tour
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5
 
Os Borger
Os BorgerOs Borger
Os Borger
 
Os Harkins
Os HarkinsOs Harkins
Os Harkins
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifm
 
Yuicss R7
Yuicss R7Yuicss R7
Yuicss R7
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Mole
 
Os Fogel
Os FogelOs Fogel
Os Fogel
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashears
 
Os Tucker
Os TuckerOs Tucker
Os Tucker
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swp
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Myths
 
Os Kimsal
Os KimsalOs Kimsal
Os Kimsal
 
Os Alrubaie
Os AlrubaieOs Alrubaie
Os Alrubaie
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholistic
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillips
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdated
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reform
 
Railsconf2007
Railsconf2007Railsconf2007
Railsconf2007
 
Oscon Mitchellbaker
Oscon MitchellbakerOscon Mitchellbaker
Oscon Mitchellbaker
 

Recently uploaded

ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
agatadrynko
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
fisherameliaisabella
 
Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...
dylandmeas
 
Kseniya Leshchenko: Shared development support service model as the way to ma...
Kseniya Leshchenko: Shared development support service model as the way to ma...Kseniya Leshchenko: Shared development support service model as the way to ma...
Kseniya Leshchenko: Shared development support service model as the way to ma...
Lviv Startup Club
 
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptxCADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
fakeloginn69
 
Digital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and TemplatesDigital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and Templates
Aurelien Domont, MBA
 
Skye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto AirportSkye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto Airport
marketingjdass
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Arihant Webtech Pvt. Ltd
 
Attending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learnersAttending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learners
Erika906060
 
The-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic managementThe-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic management
Bojamma2
 
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBdCree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
creerey
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
Lital Barkan
 
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
BBPMedia1
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
SynapseIndia
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
sarahvanessa51503
 
The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...
balatucanapplelovely
 
Unveiling the Secrets How Does Generative AI Work.pdf
Unveiling the Secrets How Does Generative AI Work.pdfUnveiling the Secrets How Does Generative AI Work.pdf
Unveiling the Secrets How Does Generative AI Work.pdf
Sam H
 
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
BBPMedia1
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for Entrepreneurs
Ben Wann
 
Project File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdfProject File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdf
RajPriye
 

Recently uploaded (20)

ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
 
Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...Discover the innovative and creative projects that highlight my journey throu...
Discover the innovative and creative projects that highlight my journey throu...
 
Kseniya Leshchenko: Shared development support service model as the way to ma...
Kseniya Leshchenko: Shared development support service model as the way to ma...Kseniya Leshchenko: Shared development support service model as the way to ma...
Kseniya Leshchenko: Shared development support service model as the way to ma...
 
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptxCADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
 
Digital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and TemplatesDigital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and Templates
 
Skye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto AirportSkye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto Airport
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
 
Attending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learnersAttending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learners
 
The-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic managementThe-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic management
 
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBdCree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
 
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
 
The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...The effects of customers service quality and online reviews on customer loyal...
The effects of customers service quality and online reviews on customer loyal...
 
Unveiling the Secrets How Does Generative AI Work.pdf
Unveiling the Secrets How Does Generative AI Work.pdfUnveiling the Secrets How Does Generative AI Work.pdf
Unveiling the Secrets How Does Generative AI Work.pdf
 
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for Entrepreneurs
 
Project File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdfProject File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdf
 

Os Furlong

  • 1. PHP Data Objects Wez Furlong Lead Architect <wez@omniti.com>
  • 2. we're hiring:  http://omniti.com/people/jobs About the author • PHP Core Developer since 2001 • Author of the Streams layer • “King” of PECL • Author of most of PDO and its drivers • Day‐job is developing the Fastest MTA on  Earth
  • 3. we're hiring:  http://omniti.com/people/jobs Coming up… • Problems with PHP DB access • PDO Solution • Features / Drivers • Installation • Getting Started • Features
  • 4. we're hiring:  http://omniti.com/people/jobs The Problem • No consistency of API between DB extensions • Sometimes no self‐consistency within a given  extension • Duplicated code (but not) • High maintenance
  • 5. we're hiring:  http://omniti.com/people/jobs The PDO Solution • Move PHP specific stuff into one extension • Database specific stuff (only) in their own  extensions • Data access abstraction, not database  abstraction
  • 6. we're hiring:  http://omniti.com/people/jobs Features Performance • Native C code beats a scripted solution • Takes advantage of latest PHP 5 internals
  • 7. we're hiring:  http://omniti.com/people/jobs Features Power • Gives you common DB features as a base • Still be able to access specialist functions
  • 8. we're hiring:  http://omniti.com/people/jobs What can it do? • Prepare/execute, bound parameters • Transactions • LOBS • Scrollable Cursors • SQLSTATE error codes, flexible error handling • Portability attributes
  • 9. we're hiring:  http://omniti.com/people/jobs Available Drivers • Pretty much all of them: • MySQL, PostgreSQL • ODBC, DB2, OCI • SQLite (2 and 3) • Sybase/FreeTDS/MSSQL • Firebird (needs love)
  • 10. we're hiring:  http://omniti.com/people/jobs Installing • Ships with PHP 5.1 • Available for PHP 5.0.x via PECL • DLLs downloadable for both on Windows via  http://pecl4win.php.net
  • 11. we're hiring:  http://omniti.com/people/jobs Building w/ PHP 5.0 ./configure  ‐‐with‐zlib ‐‐prefix=/usr/local/php5 • pear upgrade pear • pear install PDO • extension=pdo.so in your php.ini
  • 12. we're hiring:  http://omniti.com/people/jobs Building w/ PHP 5.0 • Select the driver(s) you need • pear install PDO_XXX • extension=pdo_xxx.so in your php.ini
  • 13. we're hiring:  http://omniti.com/people/jobs Installing on Win32 • Grab the DLLs from the snaps site  http://pecl4win.php.net/ • You need: – php_pdo.dll – php_pdo_XXX.dll • Put them in C:php5ext
  • 14. we're hiring:  http://omniti.com/people/jobs 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
  • 15. we're hiring:  http://omniti.com/people/jobs Connecting via PDO try { $dbh = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) { echo ”Failed to connect:” . $e‐>getMessage(); }
  • 16. we're hiring:  http://omniti.com/people/jobs DSNs • In general drivername:<driver‐specific‐stuff>
  • 17. we're hiring:  http://omniti.com/people/jobs DSNs • mysql:host=name;dbname=dbname • pgsql:native_pgsql_connection_string • odbc:odbc_dsn • oci:dbname=dbname;charset=charset
  • 18. we're hiring:  http://omniti.com/people/jobs DSNs • sqlite:/path/to/db/file • sqlite::memory: • sqlite2:/path/to/sqlite2/file • sqlite2::memory:
  • 19. we're hiring:  http://omniti.com/people/jobs 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
  • 20. we're hiring:  http://omniti.com/people/jobs DSN Aliasing • pdo.dsn.name=sqlite:/path/to/name.db $dbh = new PDO(quot;namequot;); Same as: $dbh = new PDO(quot;sqlite:/path/to/name.dbquot;);
  • 21. we're hiring:  http://omniti.com/people/jobs Connection Management try { $dbh = new PDO($dsn, $user, $pw); // use the database here // ... // done; release the connection $dbh = null; } catch (PDOException $e) { echo ”connect failed:” . $e‐>getMessage(); }
  • 22. we're hiring:  http://omniti.com/people/jobs Persistent PDO • Connection stays alive between requests $dbh = new PDO($dsn, $user, $pass, array( PDO::ATTR_PERSISTENT => true ) );
  • 23. we're hiring:  http://omniti.com/people/jobs Persistent PDO • Can specify your own cache key $dbh = new PDO($dsn, $user, $pass, array( PDO::ATTR_PERSISTENT => “my‐key” ) ); • Useful for keeping separate persistent connections
  • 24. we're hiring:  http://omniti.com/people/jobs Persistent PDO • The ODBC driver runs with connection pooling  enabled by default • “better” than PHP‐level persistence – Pool is shared at the process level • Can be forced off by setting – pdo_odbc.connection_pooling=off
  • 25. we're hiring:  http://omniti.com/people/jobs Let’s get data $dbh = new PDO($dsn); $stmt = $dbh‐>prepare( quot;SELECT * FROM FOOquot;); $stmt‐>execute(); while ($row = $stmt‐>fetch()) { print_r($row); } $stmt = null;
  • 26. we're hiring:  http://omniti.com/people/jobs Forward‐only cursors • Also known as quot;unbufferedquot; queries in mysql  parlance • They are the default cursor type • rowCount() doesn't have meaning • FAST!
  • 27. we're hiring:  http://omniti.com/people/jobs Forward‐only cursors • Other queries are likely to block • You must fetch all remaining data before  launching another query • $stmt‐>closeCursor()
  • 28. we're hiring:  http://omniti.com/people/jobs Buffered Queries $dbh = new PDO($dsn); $stmt = $dbh‐>query( quot;SELECT * FROM FOOquot;); $rows = $stmt‐>fetchAll(); $count = count($rows); foreach ($rows as $row) { print_r($row); } $stmt = null;
  • 29. we're hiring:  http://omniti.com/people/jobs Data typing • Very loose • uses strings for data • Gives you more control over data conversion • Supports integers where 1:1 mapping exists • Is float agnostic – PDO is precise
  • 30. we're hiring:  http://omniti.com/people/jobs Fetch modes • $stmt‐>fetch(PDO::FETCH_BOTH) – Array with numeric and string keys – default option • PDO::FETCH_NUM – Numeric only • PDO::FETCH_ASSOC – String only
  • 31. we're hiring:  http://omniti.com/people/jobs Fetch modes • PDO::FETCH_OBJ – stdClass object – $obj‐>name == ‘name’ column • PDO::FETCH_CLASS – You choose the class • PDO::FETCH_INTO – You provide the object
  • 32. we're hiring:  http://omniti.com/people/jobs Fetch modes • PDO::FETCH_COLUMN – Fetches only a particular column • PDO::FETCH_BOUND – Only fetches into bound variables • PDO::FETCH_FUNC – Returns the result of a callback • and more…
  • 33. we're hiring:  http://omniti.com/people/jobs Iterators $dbh = new PDO($dsn); $stmt = $dbh‐>query( quot;SELECT name FROM FOOquot;, PDO::FETCH_COLUMN, 0); foreach ($stmt as $name) { echo quot;Name: $namenquot;; } $stmt = null;
  • 34. we're hiring:  http://omniti.com/people/jobs Changing data $deleted = $dbh‐>exec( quot;DELETE FROM FOO WHERE 1quot;); $changes = $dbh‐>exec( quot;UPDATE FOO SET active=1 quot; . quot;WHERE NAME LIKE '%joe%'quot;);
  • 35. we're hiring:  http://omniti.com/people/jobs Autonumber/sequences $dbh‐>exec( quot;insert into foo values (...)quot;); echo $dbh‐>lastInsertId(); $dbh‐>exec( quot;insert into foo values (...)quot;); echo $dbh‐>lastInsertId(“seqname”); It’s up to you to call it appropriately
  • 36. we're hiring:  http://omniti.com/people/jobs Smarter queries • Quoting is annoying, but essential • PDO offers a better way $stmt = $db‐>prepare(“INSERT INTO CREDITS ” .“(extension, name) ” .“VALUES (:extension, :name)”); $stmt‐>execute(array( 'extension' => 'xdebug', 'name'      => 'Derick Rethans' ));
  • 37. we're hiring:  http://omniti.com/people/jobs Smarter queries • Quoting is annoying, but essential • PDO offers a better way $stmt = $db‐>prepare(“INSERT INTO CREDITS ” .“(extension, name) ” .“VALUES (?, ?)”); $stmt‐>execute(array( 'xdebug', 'Derick Rethans' ));
  • 38. we're hiring:  http://omniti.com/people/jobs $db‐>quote() • If you still need to quote things “by‐hand” • Currently a no‐op for the ODBC driver
  • 39. we're hiring:  http://omniti.com/people/jobs Stored Procedures $stmt = $dbh‐>prepare( quot;CALL sp_set_string(?)quot;); $stmt‐>bindParam(1, $str); $str = ‘foo’; $stmt‐>execute();
  • 40. we're hiring:  http://omniti.com/people/jobs OUT parameters $stmt = $dbh‐>prepare( quot;CALL sp_get_string(?)quot;); $stmt‐>bindParam(1, $ret, PDO::PARAM_STR, 4000); if ($stmt‐>execute()) { echo quot;Got $retnquot;; }
  • 41. we're hiring:  http://omniti.com/people/jobs IN/OUT parameters $stmt = $dbh‐>prepare( quot;call @sp_inout(?)quot;); $val = quot;My Input Dataquot;; $stmt‐>bindParam(1, $val, PDO::PARAM_STR| PDO::PARAM_INPUT_OUTPUT, 4000); if ($stmt‐>execute()) { echo quot;Got $valnquot;; }
  • 42. we're hiring:  http://omniti.com/people/jobs Binding columns for output $stmt = $dbh‐>prepare( quot;SELECT extension, name from CREDITSquot;); if ($stmt‐>execute()) { $stmt‐>bindColumn('extension', $extension); $stmt‐>bindColumn('name',      $name); while ($stmt‐>fetch(PDO::FETCH_BOUND)) { echo quot;Extension: $extensionnquot;; echo quot;Author: $namenquot;; } }
  • 43. we're hiring:  http://omniti.com/people/jobs Portability Aids • PDO aims to make it easier to write db  independent apps • Number of hacks^Wtweaks for this purpose
  • 44. we're hiring:  http://omniti.com/people/jobs Oracle style NULLs • Oracle translates empty strings into NULLs • $dbh‐>setAttribute(PDO::ATTR_ORACLE_NULLS, true); • Translates empty strings into NULLs when  fetching data • But won’t change them on insert
  • 45. we're hiring:  http://omniti.com/people/jobs Case folding • The ANSI SQL standard says that column  names are returned in upper case • High end databases (eg: Oracle and DB2)  respect this • Most others don’t $dbh‐>setAttribute(   PDO::ATTR_CASE, PDO::CASE_UPPER);
  • 46. we're hiring:  http://omniti.com/people/jobs 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 SQLSTATE  standard codes • But still offers native info too
  • 47. we're hiring:  http://omniti.com/people/jobs PDO::ERRMODE_SILENT if (!$dbh‐>query($sql)) { echo $dbh‐>errorCode() . quot;<br>quot;; $info = $dbh‐>errorInfo(); // $info[0] == $dbh‐>errorCode() //     SQLSTATE error code // $info[1] is the driver specific //     error code // $info[2] is the driver specific //     error string }
  • 48. we're hiring:  http://omniti.com/people/jobs PDO::ERRMODE_WARNING • Same as PDO::ERRMODE_SILENT • But, raises an E_WARNING as errors are  detected • You can selectively suppress the warnings  with @ operator
  • 49. we're hiring:  http://omniti.com/people/jobs PDO_ERRMODE_EXCEPTION try { $dbh‐>exec($sql); } catch (PDOException $e) { // display warning message print $e‐>getMessage(); $info = $e‐>errorInfo; // $info[0] == $e‐>code; //     SQLSTATE error code // $info[1] is the driver specific error code // $info[2] is the driver specific error string }
  • 50. we're hiring:  http://omniti.com/people/jobs Transactions $dbh‐>beginTransaction(); try { $dbh‐>query(quot;UPDATE ...quot;); $dbh‐>query(quot;UPDATE ...quot;); $dbh‐>commit(); } catch (Exception $e) { $dbh‐>rollBack(); }
  • 51. we're hiring:  http://omniti.com/people/jobs LOBs via Streams • Large objects are usually 4kb or more in size • Advantageous to avoid fetching them until  you really need to • Mature RDBMS offer LOB APIs for this • PDO exposes LOBS as Streams
  • 52. we're hiring:  http://omniti.com/people/jobs Fetching an image $db = new PDO($dsn); $stmt = $db‐>prepare( “select contenttype, imagedata” .“ from images where id=?”); $stmt‐>execute(array($_GET['id'])); $stmt‐>bindColumn(1, $type, PDO::PARAM_STR,  256); $stmt‐>bindColumn(2, $lob, PDO::PARAM_LOB); $stmt‐>fetch(PDO::FETCH_BOUND); header(quot;Content‐Type: $typequot;); fpassthru($lob);
  • 53. we're hiring:  http://omniti.com/people/jobs Inserting an image $db = new PDO($dsn); $stmt = $db‐>prepare( “insert into images ” .“(id, contenttype, imagedata) ” .“values (?, ?, ?)”); $id = get_new_id(); $fp = fopen($_FILES['file']['tmp_name'], 'rb'); $stmt‐>bindParam(1, $id); $stmt‐>bindParam(2,$_FILES['file']['type']); $stmt‐>bindParam(3, $fp, PDO::PARAM_LOB); $stmt‐>execute();
  • 54. we're hiring:  http://omniti.com/people/jobs Scrollable Cursors • Allow random access to a rowset • Higher resource usage than forward‐only  cursors • Can be used to emulate limit, offset style  paged queries • Can be used for positioned updates (more  useful for CLI/GUI apps)
  • 55. we're hiring:  http://omniti.com/people/jobs Positioned updates • An open (scrollable) cursor can be used to  target a row for another query • Name your cursor by setting  PDO::ATTR_CURSOR_NAME during prepare() • UPDATE foo set bar = ? WHERE  CURRENT OF cursor_name
  • 56. we're hiring:  http://omniti.com/people/jobs Multi‐rowset queries $stmt = $dbh‐>query( quot;call sp_multi_results()quot;); do { while($row = $stmt‐>fetch()) { print_r($row); } } while ($stmt‐>nextRowset());
  • 57. we're hiring:  http://omniti.com/people/jobs Questions? • These slides: – http://omniti.com/resources/talks • Gold: – http://troels.arvin.dk/db/rdbms/#select‐limit‐offset • Publications – google for “wez furlong pdo db2” – google for “wez furlong pdo oci” • My blog: http://netevil.org • We’re hiring: we have positions open for – PHP, Perl and C developers – a security analyst – http://omniti.com/people/jobs