PHP Data Objects Layer (PDO) Ilia Alshanetsky. What is PDO Common interface to any number of database systems. Common interface to any number of database.

Slides:



Advertisements
Similar presentations
Error HandlingPHPMay-2007 : [#] PHP Error Handling.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
PHP 5 + MySQL 5 A Perfect 10. Adam Trachtenberg PHP 5 + MySQL 5 = A Perfect mysqli extension i is for improved! All new MySQL extension for PHP.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
An Introduction to PHP Data Objects A Better Way to Interact with Your Database by Rusty Keele.
Introducing PHP Data Objects Wez Furlong
PHP Programming. Topics Background and History of PHP Installation Comments in PHP Variables Conditions Loops Functions File Handling Database Handling.
Check That Input Preventing SQL Injection Attacks By Andrew Morton For CS 410.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Dataface API Essentials Steve Hannah Web Lite Solutions Corp.
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
SQLite and PHP Wez Furlong Marcus Boerger LinuxTag 2003 Karlsruhe.
PDO, PHP Data Object Use a Database with PHP
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
PHP Data Object (PDO) Khaled Al-Sham’aa. What is PDO? PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface.
Sayed Ahmed Computer Engineering, BUET, Bangladesh MSC, Computer Science, U of Manitoba, Canada
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 19: Database Support.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
PHP With the New PDO::Informix Presented by: Thomas Beebe Advanced DataTools Corporation
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
What is MySQLi? Since the mid-90s, Mysql extension has served as the major bridge between PHP and MySQL. Although it has performed its duty quite well,
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
PHP Part 2.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 10 – MYSQL and PHP (Part 2)
Object Oriented Programming in PHP. Topics Quick OOP Review Classes Magic Methods Static Methods Inheritance Exceptions Interfaces Operators Type Hinting.
(Chapter 10 continued) Our examples feature MySQL as the database engine. It's open source and free. It's fully featured. And it's platform independent.
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
PHP PDO & PHP SOAP Introduce. Agenda What is PHP PDO and PHP SOAP? Setup PHP PDO to connect database, query database and close the connection. Setup SOAP.
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
2010/11 : [1]PHP with MySQLBuilding Web Applications using MySQL and PHP (W1) PHP with MySQL.
PHP Data Objects Wez Furlong. About the author PHP Core Developer since 2001 Author of the Streams layer “King” of PECL Author of most of PDO and its.
PHP Workshop ‹#› PHP Data Object (PDO). PHP Workshop ‹#› What is PDO? PDO is a PHP extension to formalise PHP's database connections by creating a uniform.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
PHP Workshop ‹#› أطلق إبداعك 2 أطلق إبداعك 2 مدرس معتمد من مركز زووم PHP Data Object (PDO)
Connecting to MySQL using Java By:. – Required to use Java.sql so that we can use Connection and Queries using strings. – Javax.swing.* needed for components.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
CHAPTER 10 PHP MySQL Database
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
PDOStatement Named Placeholders CIT336 - Connor Wiseman cit336.saveandquit.net/presentation.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Web Systems & Technologies
PDO Database Connections
PHP Data Objects for MySQL
ASP.NET Programming with C# and SQL Server First Edition
DEPTT. OF COMP. SC & APPLICATIONS
SQL Environment.
Web Technologies IT230 Dr Mohamed Habib.
PDO Database Connections
CPSC-310 Database Systems
PDO Database Connections
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
PDO Database Connections
Chapter 10 ADO.
Web Programming– UFCFB Lecture
Presentation transcript:

PHP Data Objects Layer (PDO) Ilia Alshanetsky

What is PDO Common interface to any number of database systems. Common interface to any number of database systems. Written in C, so you know it’s FAST! Written in C, so you know it’s FAST! Designed to make use of all the PHP 5.1 features to simplify interface. Designed to make use of all the PHP 5.1 features to simplify interface.

Why is it needed? Current state of affairs: Current state of affairs: Many native database extensions that are similar but do not provide the same interface. Many native database extensions that are similar but do not provide the same interface. In most cases, very old code that does not even scratch the surface of what PHP can offer. In most cases, very old code that does not even scratch the surface of what PHP can offer. In many instances does not account for all the capabilities offered by the database. In many instances does not account for all the capabilities offered by the database. Ex. SQLite, MySQL extensions Ex. SQLite, MySQL extensions

What Databases are Supported? At this time PDO offers the following drivers: At this time PDO offers the following drivers: MySQL 3,4,5 (depends on client libs) MySQL 3,4,5 (depends on client libs) PostgreSQL PostgreSQL SQLite 2 & 3 SQLite 2 & 3 ODBC ODBC DB2 DB2 Oracle Oracle Firebird Firebird FreeTDS/Sybase/MSSQL FreeTDS/Sybase/MSSQL

Installing PDO PDO is divided into two components PDO is divided into two components CORE (provides the interface) CORE (provides the interface) DRIVERS (access to particular database) DRIVERS (access to particular database) Ex. pdo_mysql Ex. pdo_mysql The CORE is enabled by default, drivers with the exception of pdo_sqlite are not. The CORE is enabled by default, drivers with the exception of pdo_sqlite are not.

Actual Install Steps PECL Way PECL Way pecl install pdo_[driver_name] pecl install pdo_[driver_name] Update php.ini and add extension=pdo_[driver_name].so (or.dll on win32) Update php.ini and add extension=pdo_[driver_name].so (or.dll on win32) Built into PHP Built into PHP./configure –with-pdo-[driver_name]./configure –with-pdo-[driver_name] For Win32 dlls for each driver are available. For Win32 dlls for each driver are available.

Using PDO As is the case with all database interfaces, the 1 st step involves establishing a connection. As is the case with all database interfaces, the 1 st step involves establishing a connection. // MySQL connection new PDO(‘mysql:host=localhost;dbname=testdb’, $login, $passwd); // PostgreSQL new PDO(‘pgsql:host=localhost port=5432 dbname=testdb user=john password=mypass’); // SQLite new PDO(‘sqlite:/path/to/database_file’);

What if the Connection Fails? As is the case with most native PHP objects, instantiation failure lead to an exception being thrown. As is the case with most native PHP objects, instantiation failure lead to an exception being thrown. try { $db = new PDO(…); } catch (PDOException $e) { echo $e->getMessage(); }

Persistent Connections Connecting to complex databases like Oracle is a slow process, it would be nice to re-use a previously opened connection. Connecting to complex databases like Oracle is a slow process, it would be nice to re-use a previously opened connection. $opt = array(PDO::ATTR_PERSISTENT => TRUE) ; try { $db = new PDO(“dsn”, $l, $p, $opt); } catch (PDOException $e) { echo $e->getMessage(); }

DSN INI Tricks The DSN string can be an INI setting and you can “name” as many DSNs are you like. The DSN string can be an INI setting and you can “name” as many DSNs are you like. ini_set(“pdo.dsn.ilia”, “sqlite::memory”); try { $db = new PDO(“ilia”); } catch (PDOException $e) { echo $e->getMessage(); }

Let’s Run Some Queries Query execution in PDO can be done in two ways Query execution in PDO can be done in two ways Prepared Statements (recommended for speed & security) Prepared Statements (recommended for speed & security) Direct Execution Direct Execution

Direct Query Execution Queries that modify information need to be run via exec() method. Queries that modify information need to be run via exec() method. The return value is the number of rows affected by the operation or FALSE on error. The return value is the number of rows affected by the operation or FALSE on error. $db = new PDO(“DSN”); $db->exec(“INSERT INTO foo (id) VALUES(‘bar’)”); $db->exec(“UPDATE foo SET id=‘bar’”);

Direct Query Execution Cont. In some cases “change” queries may not affect any rows and will return 0, so type-sensitive compare is essential in avoiding false positives! In some cases “change” queries may not affect any rows and will return 0, so type-sensitive compare is essential in avoiding false positives! $res = $db->exec(“UPDATE foo SET id=‘bar’”); if (!$res) // Wrong if ($res !== FALSE) // Correct

Retrieving Error Information PDO Provides 2 methods of getting error information: PDO Provides 2 methods of getting error information: errorCode() – SQLSTATE error code errorCode() – SQLSTATE error code Ex == Syntax Error Ex == Syntax Error errorInfo() – Detailed error information errorInfo() – Detailed error information Ex. array( Ex. array( [0] => 42000, [1] => 1064 [2] => You have an error in your SQL syntax; … )

Better Error Handling It stands to reason that being an OO extension PDO would allow error handling via Exceptions. It stands to reason that being an OO extension PDO would allow error handling via Exceptions. Now any query failure will throw an Exception. Now any query failure will throw an Exception. $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

Direct Execution Cont. When executing queries that retrieve information the query() method needs to be used. When executing queries that retrieve information the query() method needs to be used. On error FALSE is returned On error FALSE is returned $res = $db->query(“SELECT * FROM foo”); // $res == PDOStatement Object

Fetch Query Results Perhaps one of the biggest features of PDO is its flexibility when it comes to how data is to be fetched. Perhaps one of the biggest features of PDO is its flexibility when it comes to how data is to be fetched. Array (Numeric or Associated Indexes) Array (Numeric or Associated Indexes) Strings (for single column result sets) Strings (for single column result sets) Objects (stdClass, object of given class or into an existing object) Objects (stdClass, object of given class or into an existing object) Callback function Callback function Lazy fetching Lazy fetching Iterators Iterators And more! And more!

Array Fetching $res = $db->query(“SELECT * FROM foo”); while ($row = $res->fetch(PDO::FETCH_NUM)){ // $row == array with numeric keys } $res = $db->query(“SELECT * FROM foo”); while ($row = $res->fetch(PDO::FETCH_ASSOC)){ // $row == array with associated (string) keys } $res = $db->query(“SELECT * FROM foo”); while ($row = $res->fetch(PDO::FETCH_BOTH)){ // $row == array with associated & numeric keys }

Fetch as String Many applications need to fetch data contained within just a single column. Many applications need to fetch data contained within just a single column. $u = $db->query(“SELECT users WHERE login=‘login’ AND password=‘password’”); // fetch(PDO::FETCH_COLUMN) if ($u->fetchColumn()) { // returns a string // login OK } else { /* authentication failure */ }

Fetch as Standard Object You can fetch a row as an instance of stdClass where column name == property name. You can fetch a row as an instance of stdClass where column name == property name. $res = $db->query(“SELECT * FROM foo”); while ($obj = $res->fetch(PDO::FETCH_OBJ)) { // $obj == instance of stdClass }

Fetch Into a Class PDO allows the result to be fetched into a class type of your choice. PDO allows the result to be fetched into a class type of your choice. $res = $db->query(“SELECT * FROM foo”); $res->setFetchMode( PDO::FETCH_CLASS, “className”, array(‘optional’=‘Constructor Params’) ); while ($obj = $res->fetch()) { // $obj == instance of className }

Fetch Into a Class Cont. PDO allows the query result to be used to determine the destination class. PDO allows the query result to be used to determine the destination class. $res = $db->query(“SELECT * FROM foo”); $res->setFetchMode( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE ); while ($obj = $res->fetch()) { // $obj == instance of class who’s name is // found in the value of the 1 st column }

Fetch Into an Object PDO even allows retrieval of data into an existing object. PDO even allows retrieval of data into an existing object. $u = new userObject; $res = $db->query(“SELECT * FROM users”); $res->setFetchMode(PDO::FETCH_INTO, $u); while ($res->fetch()) { // will re-populate $u with row values }

Result Iteration PDOStatement implements Iterator interface, which allows for a method-less result iteration. PDOStatement implements Iterator interface, which allows for a method-less result iteration. $res = $db->query( “SELECT * FROM users”, PDO::FETCH_ASSOC ); foreach ($res as $row) { // $row == associated array representing // the row’s values. }

Lazy Fetching Lazy fetches returns a result in a form object, but holds of populating properties until they are actually used. Lazy fetches returns a result in a form object, but holds of populating properties until they are actually used. $res = $db->query( “SELECT * FROM users”, PDO::FETCH_LAZY ); foreach ($res as $row) { echo $row[‘name’]; // only fetch name column }

fetchAll() The fetchAll() allows retrieval of all results from a query right away. (handy for templates) The fetchAll() allows retrieval of all results from a query right away. (handy for templates) Can be quite memory intensive for large results sets! Can be quite memory intensive for large results sets! $qry = “SELECT * FROM users”; $res = $db->query($qry)->fetchAll( PDO::FETCH_ASSOC ); // $res == array of all result rows, where each row // is an associated array.

Callback Function PDO also provides a fetch mode where each result is processed via a callback function. PDO also provides a fetch mode where each result is processed via a callback function. function draw_message($subject,$ ) { … } $res = $db->query(“SELECT * FROM msg”); $res->fetchAll( PDO::FETCH_FUNC, “draw_message” );

Direct Query Problems Query needs to be interpreted on each execution can be quite waste for frequently repeated queries. Query needs to be interpreted on each execution can be quite waste for frequently repeated queries. Security issues, un-escaped user input can contain special elements leading to SQL injection. Security issues, un-escaped user input can contain special elements leading to SQL injection.

Escaping in PDO Escaping of special characters in PDO is handled via the quote() method. Escaping of special characters in PDO is handled via the quote() method. $qry = “SELECT * FROM users WHERE login=“.$db->quote($_POST[‘login’]).” AND passwd=“.$db->quote($_POST[‘pass’]);

Prepared Statements Compile once, execute as many times as you want. Compile once, execute as many times as you want. Clear separation between structure and input, which prevents SQL injection. Clear separation between structure and input, which prevents SQL injection. Often faster then query()/exec() even for single runs. Often faster then query()/exec() even for single runs.

Prepared Statements in Action $stmt = $db->prepare( “SELECT * FROM users WHERE id=?” ); $stmt->execute(array($_GET[‘id’])); $stmt->fetch(PDO::FETCH_ASSOC);

Bound Parameters Prepared statements parameters can be given names and bound to variables. Prepared statements parameters can be given names and bound to variables. $stmt = $db->prepare( “INSERT INTO users VALUES(:name,:pass,:mail)”); foreach (array(‘name’,’pass’,’mail’) as $v) $stmt->bindParam(‘:’.$v,$$v); $fp = fopen(“./users”, “r”); while (list($name,$pass,$mail) = fgetcsv($fp,4096)) { $stmt->execute(); }

Bound Result Columns Result columns can be bound to variables as well. Result columns can be bound to variables as well. $qry = “SELECT :type, :data FROM images LIMIT 1”; $stmt = $db->prepare($qry); $stmt->bindColumn(‘:type’,$type); $stmt->bindColumn(‘:type’,STDOUT,PDO::PARAM_LOB); $stmt->execute(PDO::FETCH_BOUND); header(“Content-Type: “.$type);

Partial Data Retrieval In some instances you only want part of the data on the cursor. To properly end the cursor use the closeCursor() method. In some instances you only want part of the data on the cursor. To properly end the cursor use the closeCursor() method. $res = $db->query(“SELECT * FROM users”); foreach ($res as $v) { if ($res[‘name’] == ‘end’) { $res->closeCursor(); break; }

Transactions Nearly all PDO drivers talk with transactional DBs, so PDO provides handy methods for this purpose. Nearly all PDO drivers talk with transactional DBs, so PDO provides handy methods for this purpose. $db->beginTransaction(); if ($db->exec($qry) === FALSE) { $db->rollback(); } $db->commit();

Metadata Like most native database interfaces PDO provides means of accessing query metadata. Like most native database interfaces PDO provides means of accessing query metadata. $res = $db->query($qry); $ncols = $res->columnCount(); for ($i=0; $i < $ncols; $i++) { $meta_data = $stmt->getColumnMeta($i); }

getColumnMeta() Result native_type – PHP data type native_type – PHP data type driver:decl_type - The data type of the column according to the database. driver:decl_type - The data type of the column according to the database. flags – will return any flags particular to this column in a form of an array. flags – will return any flags particular to this column in a form of an array. name – the name of the column as returned by the database without any normalization. name – the name of the column as returned by the database without any normalization. len – maximum length of a string column, may not always be available, will be set to -1 if it isn’t. len – maximum length of a string column, may not always be available, will be set to -1 if it isn’t. precision - The numeric precision of this column. precision - The numeric precision of this column. pdo_type - The column type according to PDO as one of the PDO_PARAM constants. pdo_type - The column type according to PDO as one of the PDO_PARAM constants.

lastInsertId() Many databases have unique identifier assigned to each newly inserted row. PDO provides access to this value via lastInsertId() method. Many databases have unique identifier assigned to each newly inserted row. PDO provides access to this value via lastInsertId() method. Can take optional sequence name as parameter. Can take optional sequence name as parameter. Useful for PostgreSQL Useful for PostgreSQL if ($db->exec(“INSERT INTO …”)) { $id = $db->lastInsertId(); }

Connection Information Some connection information can be obtained via the getAttribute() PDO method. Some connection information can be obtained via the getAttribute() PDO method. $db->getAttribute(PDO::ATTR_SERVER_VERSION); // Database Server Version $db->getAttribute(PDO::ATTR_CLIENT_VERSION); // Client Library Server Version $db->getAttribute(PDO::ATTR_SERVER_INFO); // Misc Server information $db->getAttribute(PDO::ATTR_CONNECTION_STATUS); // Connection Status

Extending PDO class DB extends PDO { function query($qry, $mode=NULL) { $res = parent::query($qry, $mode); if (!$res) { var_dump($qry, $this->errorInfo()); return null; } else { return $res; }

Questions