SlideShare a Scribd company logo
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

ODP
Adodb Pdo Presentation
PPT
PHP - PDO Objects
ODP
Database Connection With Mysql
PPT
MYSQL - PHP Database Connectivity
PDF
Introduction to php database connectivity
PDF
PHP and Mysql
PDF
Quebec pdo
Adodb Pdo Presentation
PHP - PDO Objects
Database Connection With Mysql
MYSQL - PHP Database Connectivity
Introduction to php database connectivity
PHP and Mysql
Quebec pdo

What's hot (20)

PPT
Php MySql For Beginners
PPTX
Database Connectivity in PHP
PPT
Introducing PHP Data Objects
PDF
lab56_db
PPT
Database presentation
PPTX
Cake PHP 3 Presentaion
PPT
PHP - Getting good with MySQL part II
PPT
PHP and MySQL
PDF
4.3 MySQL + PHP
PDF
Getting Started with PL/Proxy
ODP
PHP Data Objects
PDF
Web 10 | PHP with MySQL
PPT
Php classes in mumbai
PPT
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PPT
Php Data Objects
PDF
Web 11 | AJAX + JSON + PHP
PDF
The Beauty And The Beast Php N W09
PDF
Web 8 | Introduction to PHP
PPTX
Mysql
PPTX
System performance tuning
Php MySql For Beginners
Database Connectivity in PHP
Introducing PHP Data Objects
lab56_db
Database presentation
Cake PHP 3 Presentaion
PHP - Getting good with MySQL part II
PHP and MySQL
4.3 MySQL + PHP
Getting Started with PL/Proxy
PHP Data Objects
Web 10 | PHP with MySQL
Php classes in mumbai
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
Php Data Objects
Web 11 | AJAX + JSON + PHP
The Beauty And The Beast Php N W09
Web 8 | Introduction to PHP
Mysql
System performance tuning
Ad

Similar to PDO Basics - PHPMelb 2014 (20)

PPTX
Php Training Workshop by Vtips
PPT
Intro to php
PPTX
Php with mysql ppt
PDF
Php summary
PDF
phptut4
PDF
phptut4
PPTX
Phphacku iitd
KEY
Scaling php applications with redis
PPTX
Web Application Development using PHP Chapter 7
PPTX
PHP for hacks
PPTX
HackU PHP and Node.js
PPTX
PHP and MySQL.pptx
PPTX
PHP language presentation
PDF
PHP with MySQL
PPTX
working with PHP & DB's
PDF
CakePHP
PDF
Php Applications with Oracle by Kuassi Mensah
PPTX
PHP Basics and Demo HackU
PDF
Codeigniter
PPTX
Lecture9_OOPHP_SPring2023.pptx
Php Training Workshop by Vtips
Intro to php
Php with mysql ppt
Php summary
phptut4
phptut4
Phphacku iitd
Scaling php applications with redis
Web Application Development using PHP Chapter 7
PHP for hacks
HackU PHP and Node.js
PHP and MySQL.pptx
PHP language presentation
PHP with MySQL
working with PHP & DB's
CakePHP
Php Applications with Oracle by Kuassi Mensah
PHP Basics and Demo HackU
Codeigniter
Lecture9_OOPHP_SPring2023.pptx
Ad

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MYSQL Presentation for SQL database connectivity
sap open course for s4hana steps from ECC to s4
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MIND Revenue Release Quarter 2 2025 Press Release
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Per capita expenditure prediction using model stacking based on satellite ima...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I

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