dpc2007 php and oracle (kuassi mensah)
DESCRIPTION
Dutch PHP Conference 2007TRANSCRIPT
<Insert Picture Here>
PHP and Oracle - Best Practices and Roadmap
Kuassi MensahGroup Product Manager, Java Platform Grouphttp://db360.blogspot.com
PHP and Oracle Best Practices and Roadmap
• Oracle and PHP• PHP Oracle Extensions• Best Practices for Performance and Scalability• What’s New for PHP in Oracle Database 11g
Oracle Commitments to PHP
• Long time commitment to PHP• Thousands of developers use Oracle and PHP• Oracle in various PHP communities and expert groups
• Participate to PHP Events and Conferences• Submit Bug Fixes back to the Community
PHP Extensions – Take your Pick
NET Functions, Apache-specific Functions, Alternative PHP Cache, Advanced PHP debugger, Array Functions, Aspell functions [deprecated],BCMath Arbitrary Precision Mathematics Functions, PHP bytecode Compiler, Bzip2 Compression Functions, Calendar Functions, CCVS API Functions [deprecated], Class/Object Functions, Classkit Functions, ClibPDF Functions, COM and .Net (Windows), Crack Functions, Character Type Functions, CURL, Client URL Library Functions, Cybercash Payment Functions, Credit Mutuel CyberMUT functions, Cyrus IMAP administration Functions, Date and Time Functions, DB++ Functions, Database (dbm-style) Abstraction Layer Functions, dBase Functions, DBM Functions [deprecated], dbx Functions, Direct IO Functions, Directory Functions, DOM Functions, DOM XML Functions, enchant Functions, Error Handling and Logging Functions, Exif Functions, Expect Functions, File Alteration Monitor Functions, Forms Data Format Functions,Fileinfo Functions, filePro Functions, Filesystem Functions, Filter Functions, Firebird/InterBase Functions, Firebird/Interbase Functions (PDO_FIREBIRD), FriBiDi Functions, FrontBase Functions, FTP Functions, Function Handling Functions, GeoIP Functions, Gettext, GMP Functions, gnupg Functions, Net_Gopher, hash Functions, HTTP, Hyperwave Functions, Hyperwave API Functions, IBM DB2, Cloudscape and Apache Derby Functions, ICAP Functions [removed], iconv Functions, ID3 Functions, IIS Administration Functions, Image Functions, IMAP, POP3 and NNTP Functions, Informix Functions, Informix Functions (PDO_INFORMIX), Ingres II Functions, IRC Gateway Functions, PHP / Java Integration, JSON Functions, KADM5, LDAP Functions, libxml Functions, Lotus Notes Functions, LZF Functions, Mail Functions, mailparseFunctions, Mathematical Functions, MaxDB PHP Extension, MCAL Functions, Mcrypt Encryption Functions, MCVE (Monetra) Payment Functions, Memcache Functions, Mhash Functions, Mimetype Functions, Ming functions for Flash, Miscellaneous Functions, mnoGoSearchFunctions, Microsoft SQL Server Functions, Microsoft SQL Server and Sybase Functions (PDO_DBLIB), Mohawk Software Session Handler Functions, mSQL Functions, Multibyte String Functions, muscat Functions, MySQL Functions, MySQL Functions (PDO_MYSQL), MySQLImproved Extension, Ncurses Terminal Screen Control Functions, Network Functions, Newt Functions, NSAPI-specific Functions, Object Aggregation/Composition Functions, Object property and method call overloading, Oracle Functions, ODBC Functions (Unified), ODBC and DB2 Functions (PDO_ODBC), oggvorbis, OpenAL Audio Bindings, OpenSSL Functions, Oracle Functions [deprecated], Oracle Functions (PDO_OCI), Output Control Functions, Ovrimos SQL Functions, Paradox File Access, Parsekit Functions, Process Control Functions, Regular Expression Functions (Perl-Compatible), PDF Functions, PDO Functions, PHP Options&Information, POSIX Functions, Regular Expression Functions (POSIX Extended), PostgreSQL Functions, PostgreSQL Functions (PDO_PGSQL), Printer Functions, Program Execution Functions, PostScript document creation, Pspell Functions, qtdom Functions, Radius, Rar Functions, GNU Readline, GNU Recode Functions, RPM Header Reading Functions, runkit Functions, Satellite CORBA client extension [deprecated], SDO Functions, SDO XML Data Access Service Functions, SDO Relational Data Access Service Functions, Semaphore, Shared Memory and IPC Functions, SESAM Database Functions, PostgreSQLSession Save Handler, Session Handling Functions, Shared Memory Functions, SimpleXML functions, SNMP Functions, SOAP Functions, Socket Functions, Standard PHP Library (SPL) Functions, SQLite Functions, SQLite Functions (PDO_SQLITE), Secure Shell2 Functions, Statistics Functions, Stream Functions, String Functions, Shockwave Flash Functions, Sybase Functions, TCP Wrappers Functions, Tidy Functions, Tokenizer Functions, Unicode Functions, URL Functions, Variable Handling Functions, Verisign Payflow Pro Functions, vpopmailFunctions, W32api Functions, WDDX Functions, win32ps Functions, win32service Functions, xattr Functions, xdiff Functions, XML Parser Functions, XML-RPC Functions, XMLReader functions, xmlwriter Functions, XSL functions, XSLT Functions, YAZ Functions, YP/NIS Functions, Zip File Functions, Zlib Compression Functions,
PHP Oracle Extensions
• OCI8 Extension • Improved/Refactored• Zend Core for Oracle: Joint effort with Zend
• Prebuilt stack (Apache, PHP, OCI8 Extension, and Oracle Instant Client driver)
• Enterprise support from Zend• php.net• PECL• Used by ADOdb, PEAR DB and PEAR MDB2
• PDO_OCI• php.net• PECL
PHP/Oracle: How They Stack Up
Oracle Database8i, 9i or 10gWeb User Mid Tier
Apache
PHP
OCI8 Extension
Oracle Client Libraries 8i, 9i or 10g
OCI8 Extension
• Example<?php
$c = oci_connect('hr', 'hrpw', 'localhost/XE');
$s = oci_parse($c, 'select city from locations');
oci_execute($s);
while ($r = oci_fetch_assoc($s))
echo $r['CITY'] . "<br>";
?>
Easy Connect[//]host[:port][/service_name]
PHP and Oracle Best Practices and Roadmap
• Oracle and PHP• PHP Oracle Extensions
Best Practices for Performance and Scalability• What’s New for PHP in Oracle Database 11g
PHP/Oracle: Best Practices for Performance and Scalability
• Connection Management• Statement Management • Transaction Management• Globalization
<Insert Picture Here>
Connection Management
OCI8 Connections
• Non-Persistent Connections• Standard Connection • Multiple Unique Connections
• Persistent Connections
Non Persistent Connections
Standard Connection$c = oci_connect($username, $password, $dbname);
• Connection bound to the life of the script• Second oci_connect() in script returns same DB connection
Multiple Unique Connections$c = oci_new_connect($username, $password,$dbname);
• Connection bound to the life of the script• Each oci_new_connect() returns a new DB connection• Use for independent operationsCosts of Non-Persistent Connections• High connect times• Unnecessary connect/disconnect CPU load
Persistent Connections are Cached
user:db:charset:privilegehr:XE:ALU32UTF8:normalsystem:XE:ALU32UTF8:sysdba
oci_pconnect()
Connection Cache
Persistent Connections
$c = oci_pconnect($username, $password, $dbname);
• Not automatically closed at script completion• Fast for subsequent connections
• But holds resources when application idle
• Configurable in php.inioci8.max_persistent
oci8.persistent_timeout
oci8.ping_interval
Costs of Persistent Connections• Too many connections hanging around• May Allocate too much memory• Significant number not doing work
<Insert Picture Here>
Statement Management
SQL Statement Execution
The Steps for Executing a SQL Statement with OCI8:• Parse - oci_parse
• Prepares a statement for execution
• Bind - oci_bind_by_name
• Optionally binds variables in WHERE clause
• Execute – oci_execute
• The Database executes the statement and buffers the results
• Fetch - oci_fetch_all• Optionally retrieves results from the database
Statement Tuning Reduce Round Trips b/w PHP & Oracle
Round Trip
• Row Prefetching• Server-side Statement Caching• Client-side Statement Caching
Row Prefetching
Oracle Client Libraries
OCI8 Extension
Beijing
Database
BeijingBernBombay. . .
Set oci8.default_prefetch
PHP
Reduces round trips
OCI8 Prefetch Rows
• “prefetched rows” are cached internally by Oracle• Improves query performance by reducing “round trips”
• Default Prefetch Size in php.inioci8.default_prefetch = 10
• Maximum number of rows in each DB "round trip"• Memory limit of 1024 * oci8.default_prefetch is
also set
• Value can also be set inlineoci_set_prefetch($s, 100);
Statement: No Bind Variables
select col from tabwhere v = 1
select col from tabwhere v = 2
select col from tabwhere v = 1
select col from tabwhere v = 2
1: select col from tab where v = 12: select col from tab where v = 2
Database cache
Poor use of db pool
Statement Caching: Bind Variables
select col from tabwhere v = :bv
select col from tabwhere v = :bv
select col from tabwhere v = :bv
select col from tabwhere v = :bv
1: select col from tab where v = :bv
Database cache
Server-side Statement cache
Increasesperformanceand security
Statement Caching - OCI8 Bind
$s = oci_parse($c,"select last_name from employees
where employee_id = :eidbv");
$myeid = 101;
oci_bind_by_name($s, ":EIDBV", $myeid);
oci_execute($s);
oci_fetch_all($s, $res);
echo "Last name is:" .$res['LAST_NAME'][0]."<br>\n";
$myeid = 102;
oci_execute($s); // No need to re-parse
oci_fetch_all($s, $res);
echo "Last name is: "
. $res['LAST_NAME'][0] ."<br>\n";
Client-side Statement Caching
select col from tab
select col from tab
select col from tab
“Use statement 1”
1: select col from tab
Database cache
Set oci8.statement_cache_size
1: select col from tab
Client cache
OCI8 Client-side Statement Cache
• OCI8 extension has client side statement cache• php.ini
oci8.statement_cache_size = 20
• Moves statement cache management load from DB to PHP side
• Uses memory on PHP side for cached statement handles
• Uses memory on DB for session cursors
<Insert Picture Here>
Transaction Management
Auto Commit
By default oci_execute() auto-commitsfunction do_simple_insert($conn, $array)
{
foreach ($array as $v) {
$s = oci_parse($conn,
"insert into ptab (pdata) values ('".$v."')");
$r = oci_execute($s);
}
}
This is slow and not a not a good practice
Explicit Commit
function do_transactional_insert($conn, $array)
{
$s = oci_parse($conn,
'insert into ptab (pdata) values (:bv)');
oci_bind_by_name($s, ':bv', $v, 20, SQLT_CHR);
foreach ($array as $v)
$r = oci_execute($s, OCI_DEFAULT);
oci_commit($con);
}
This is fast
Bulk Inserts (PHP Code)
function do_bulk_insert($conn, $array)
{
$s = oci_parse($conn,
'begin mypkg.myproc(:c1); end;');
oci_bind_array_by_name($s, ":c1", $array,
count($array), -1, SQLT_CHR);
oci_execute($s);
}
Could be fastest
Bulk Inserts (PL/SQL Stored Proc.)create or replace package mypkg as
type arrtype is table of varchar2(20)
index by pls_integer;
procedure myproc(p1 in arrtype);
end mypkg;
create or replace package body mypkg as
procedure myproc(p1 in arrtype) is
begin
forall i in indices of p1
insert into ptab values (p1(i));
end myproc;
end mypkg;
Globalization
• Globalization in OCI8 is built-in, inherited from OCI• Mostly transparent to PHP applications
• NLS_LANG defines the Oracle Locale<language>_<territory>.<character set>
GERMAN.GERMANY.AL32UTF8
• Retrieve User Locale from the Browser ISO locale setting$s = $_SERVER[“HTTP_ACCEPT_LANGUAGE”]
• Multibytes character manipulation requires PHP mbstring or iconvlibraries- Enable mbstring extension - set mbstring.func_overload
• PHP applications that call PL/SQL should also map ISO locale to NLS_LANGUAGE and NLS_TERRITORY
• See “The Underground PHP and Oracle Manual” for more details.
PHP and Oracle Best Practices and Roadmap
• Oracle and PHP• PHP Oracle Extensions• Best Practices for Performance and Scalability
What’s New for PHP in Oracle Database 11g
Will be including New Features for PHP as soon as the Oracle Database 11g is announced, pretty soon!Apologies for the delay.
Kuassi Mensah
Oracle PHP Developer Center
OTN PHP Developer Center
• www.oracle.com/technology/php• Underground PHP and Oracle Manual• Articles, FAQs, links to blogs, JDeveloper PHP Extension,
Zend Core for Oracle• ISVs and hardware vendors
oraclepartnernetwork.oracle.com• Contacts/Blogs
• [email protected]• [email protected]• blogs.oracle.com/opal• db360.blogspot.com