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

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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