SlideShare a Scribd company logo
1 of 13
Download to read offline
PHP 101
Data Persistance (Database Basics)
•

Most PHP applications need to store data

•

Most PHP applications store this data into a database of some kind

•

PHP supports many kinds of databases (Mysql, Microsoft SQL,
postgresql, Oracle)

•

We’re not going to talk about Document based data stores today
(no-sql)
•

To use a database in PHP you need to do 3 things
•

Connect to the database

•

Query the database using SQL

•

Do something with the result

•

Close the connection to the database
•

Early in PHP this was achieved by using DB specific functions
•

mysqli_connect(host, username, password, dnname);

•

mysqli_query($connection, $sql);

•

mysqli_fetch_array($recordset);

•

mysqli_close($connection);
•

Easy!

•

Not very transferable however

•

What happens if you change database?

•

Mucho refactoring required - $$$

•

That said this is how sites like W3Schools still teach and it’s a good
place to start.

•

But is there a better way?
Of course there is!
•

PDO - PHP Data Objects
•

Creates a standardised foundation to connect to databases that
can be queried using mysql (remember no no-sql here)

•

This includes: cubrid, firebird, interbase, DB2, informix, MSSQL
server, mysql, postgresql, sqlite, 4d… you get the idea…

•

You can check out which drivers you have installed by: <?php
print_r(PDO::getAvailableDrivers()); ?>
•

So remember with databases we do the following:
•

Connect

•

Query

•

Do something with the result

•

Close the connection
•

Connect
•

•

•

<php $DBH = new PDO("mssql:host=$host;dbname=
$dbname, $user, $pass”); ?>
<?php $DBH = new PDO(“sqlite:my/database/path/
database.db"); ?>

You should always wrap your PDO operations in a try/catch as PDO
uses exceptions to trap errors. (there are 3 modes
ERRMODE_SILENT, ERRMODE_WARNING, ERRMODE_EXEPTION)
•

Query
•

PDO uses a Prepare/Bind/Execute pattern (good for stopping SQL injection)

•

<?php 

$query = $DBH->prepare("INSERT INTO phpmelb ( first_name ) values ( 'Andrew' )");

$query->execute();

?>

•

You can do this in one call using the exec method but this means you can’t use prepared
statements. Exec is good for queries that have no results such as delete
($query>exec('DELETE FROM phpmelb WHERE 1’);)

•

You can do this in one call using the exec method but this means you can’t use prepared
statement features like named place holders.
•

Do something with the result
•

You get data with the fetch() method but you have to tell PDO how you want
the data to be fetched.

•

<?php

$query = $DBH->query('SELECT name from phpmelb);

$query->setFetchMode(PDO::FETCH_ASSOC); 

while($row = $query->fetch()) { 

echo $row['name'] . "n";

}

•

$query->setFetchMode(PDO::FETCH_OBJ) creates an object for each result
•

Close the connection
•

<php $DBH = null; ?>

•

You just set the handle to null

•

PDO does support persistent connections
•

That’s it!
•

There are a number of helper methods like getlastid etc.

•

And loads more to learn (stored procedures, transactions etc etc)

•

Check out the docs. 

http://www.php.net/manual/en/intro.pdo.php

More Related Content

What's hot

Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
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
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
hiren.joshi
 

What's hot (20)

Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
lab56_db
lab56_dblab56_db
lab56_db
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
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 ...
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Mysql
MysqlMysql
Mysql
 
System performance tuning
System performance tuningSystem performance tuning
System performance tuning
 

Similar to PDO Basics - PHPMelb 2014

HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 

Similar to PDO Basics - PHPMelb 2014 (20)

Php Training Workshop by Vtips
Php Training Workshop by VtipsPhp Training Workshop by Vtips
Php Training Workshop by Vtips
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
Php summary
Php summaryPhp summary
Php summary
 
phptut4
phptut4phptut4
phptut4
 
phptut4
phptut4phptut4
phptut4
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
CakePHP
CakePHPCakePHP
CakePHP
 
Php Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi MensahPhp Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi Mensah
 
PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 

Recently uploaded

Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 

PDO Basics - PHPMelb 2014

  • 1. PHP 101 Data Persistance (Database Basics)
  • 2. • Most PHP applications need to store data • Most PHP applications store this data into a database of some kind • PHP supports many kinds of databases (Mysql, Microsoft SQL, postgresql, Oracle) • We’re not going to talk about Document based data stores today (no-sql)
  • 3. • To use a database in PHP you need to do 3 things • Connect to the database • Query the database using SQL • Do something with the result • Close the connection to the database
  • 4. • Early in PHP this was achieved by using DB specific functions • mysqli_connect(host, username, password, dnname); • mysqli_query($connection, $sql); • mysqli_fetch_array($recordset); • mysqli_close($connection);
  • 5. • Easy! • Not very transferable however • What happens if you change database? • Mucho refactoring required - $$$ • That said this is how sites like W3Schools still teach and it’s a good place to start. • But is there a better way?
  • 7. • PDO - PHP Data Objects • Creates a standardised foundation to connect to databases that can be queried using mysql (remember no no-sql here) • This includes: cubrid, firebird, interbase, DB2, informix, MSSQL server, mysql, postgresql, sqlite, 4d… you get the idea… • You can check out which drivers you have installed by: <?php print_r(PDO::getAvailableDrivers()); ?>
  • 8. • So remember with databases we do the following: • Connect • Query • Do something with the result • Close the connection
  • 9. • Connect • • • <php $DBH = new PDO("mssql:host=$host;dbname= $dbname, $user, $pass”); ?> <?php $DBH = new PDO(“sqlite:my/database/path/ database.db"); ?> You should always wrap your PDO operations in a try/catch as PDO uses exceptions to trap errors. (there are 3 modes ERRMODE_SILENT, ERRMODE_WARNING, ERRMODE_EXEPTION)
  • 10. • Query • PDO uses a Prepare/Bind/Execute pattern (good for stopping SQL injection) • <?php 
 $query = $DBH->prepare("INSERT INTO phpmelb ( first_name ) values ( 'Andrew' )");
 $query->execute();
 ?> • You can do this in one call using the exec method but this means you can’t use prepared statements. Exec is good for queries that have no results such as delete ($query>exec('DELETE FROM phpmelb WHERE 1’);) • You can do this in one call using the exec method but this means you can’t use prepared statement features like named place holders.
  • 11. • Do something with the result • You get data with the fetch() method but you have to tell PDO how you want the data to be fetched. • <?php
 $query = $DBH->query('SELECT name from phpmelb);
 $query->setFetchMode(PDO::FETCH_ASSOC); 
 while($row = $query->fetch()) { 
 echo $row['name'] . "n";
 } • $query->setFetchMode(PDO::FETCH_OBJ) creates an object for each result
  • 12. • Close the connection • <php $DBH = null; ?> • You just set the handle to null • PDO does support persistent connections
  • 13. • That’s it! • There are a number of helper methods like getlastid etc. • And loads more to learn (stored procedures, transactions etc etc) • Check out the docs. 
 http://www.php.net/manual/en/intro.pdo.php