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

Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For BeginnersPriti Solanki
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
Database presentation
Database presentationDatabase presentation
Database presentationwebhostingguy
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaionglslarmenta
 
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 IIFirdaus Adib
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/ProxyPeter Eisentraut
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
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 Objectshiren.joshi
 
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 W09Bastian Feder
 
System performance tuning
System performance tuningSystem performance tuning
System performance tuningMenandro Oba
 

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

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Dernier (20)

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

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