SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à PDO Basics - PHPMelb 2014

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

Similaire à 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
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
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
 

Dernier (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
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
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

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