SlideShare a Scribd company logo
PHP Performance 101:
so you need to use a database
Leon Fayer
@papa_fire
Who am I ?
• 20+ years development and operations of web applications
• currently Vice President at OmniTI
• can be found online:
• @papa_fire
• github:lfayer
• http://fayerplay.com
• https://joind.in/talk/view/11914
what it is about
databases & performance
what it’s not about
NoSQL MySQL
how database connection works
① establish connection
② send query
③ process query
④ send result
⑤ close connection
common database connection
$dbh = new DB(…);
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetchAll();
$dbh = null;
common database connection
① var $dbh = new DB(…);
② var $sth = $dbh->prepare($query);
① $sth->execute();
② var $result = $sth->fetchAll();
③ $dbh = null;
① establish connection
① establish connection
⑤ close connection
and
problem
connection overhead
visual representation
①
①
①
⑤
⑤
⑤
short answer
persistent connections
short and helpful answer
persistent connections
avoid multiple connections
how it works (high level)
①
①
①
⑤
⑤
⑤
①
⑤
conclusion
reduce # of connections
② send query
most common problem
n+1
n+1
// get a list of items
$sth = $dbh->prepare("select item_id from items
where active = true");
$sth->execute();
$items = $sth->fetchAll();
// get properties for each items
foreach ($items as $i) {
$sth_prop = $dbh->prepare("select * from
item_properties where item_id = ?");
$sth_prop->execute($item);
$item_list[$i[‘item_id’]][‘props’] = $sth_prop->fetchAll();
$item_list[$i[‘item_id’]][‘id’] = $i[‘id’];
}
n+1 you don’t know about
// get a list of items
$items = get_active_item_ids();
// get properties for each items
foreach ($items as $i) {
$item = Item->new($i[‘item_id’])
$item_list[$i[‘item_id’][‘id’] = $item->item_id;
$item_list[$i[‘item_id’]][‘props’] = $item->properties();
}
easy solution
// get a list of items with properties
$sth = $dbh->prepare("select i. item_id, p.* from items i,
item_properties p
where i.item_id = p.item_id
and active = true");
$sth->execute();
$items = $sth->fetchAll();
// arrange object to your liking
foreach ($items as $i) {
$item_list[$i[‘item_id’]][‘props’] = $i;
$item_list[$i[‘item_id’]][‘id’] = $i[‘id’];
}
conclusion
limit number of queries
cool stuff
:BONUS:
Common Table Expressions
(CTEs)
* MySQL does not support CTEs
// create temp table naughty_users
// and get data from it
with naughty_users as (
select * from users where banned = 1
)
select userid, email from naughty_users;
even more cool
Writeable
Common Table Expressions
* Postgres 9.1+ only
multiple queries are required
// create user record
insert into users (name, email) values (?,?) returning
userid
// create address record
insert into addresses (userid, address, city, state,
zip) values (?,?,?,?,?) returning addressid
// track changes to user information
insert into user_history (userid, addressid, action)
values (?,?,?) returning historyid
or are they?
with userdata as (
insert into users (name, email) values (?,?)
returning userid
), addressdata as (
insert into addresses (userid, address, city, state, zip)
select userid,?,?,?,? from userdata
returning addressid
), historydata as (
insert into user_history (userid, addressid, action)
select userid, addressid,?
from userdata, addressdata
returning historyid
)
select userid, addressid, historyid
from userdata, addressdata, historydata;
why not use transactions?
• no complicated transaction code
• no complicated error handling code
• reduced query overhead
• better performance
find out more
For more details:
http://omniti.com/seeds/writable-ctes-improve-performance
③ process query
unpopular opinion
ORMs are evil
why?
1. machine-generated
2. object construction overhead
3. false sense of control
in one sentence
you have no idea how it works
timely tweet
conclusion
learn SQL
④ send results
may be shocking, but …
databases can do math
illustrating wrong
// get all orders
$sth = $dbh->prepare("select order_id, price from orders");
$sth->execute();
$orders= $sth->fetchAll();
//order by order_id
usort($orders, function ($a, $b) { if ($a['order_id'] == $b['order_id']) { return 0; }
return $a['order_id'] < $b['order_id'] ? -1 : 1; });
// get average $ for last 10 orders
$count = 1;
$total = 0;
$avg = 0;
foreach ($orders as $order) {
$total += $order[‘price’];
if ($count == 10) {
$avg = $total/$count;
break 1;
}
$count++;
}
vs right
// get average $ for last 10 orders
$sth = $dbh->prepare("select avg(price) as avg_price
from (select price from orders
order by order_id desc limit 10) ");
$sth->execute();
$orders= $sth->fetchAll();
$avg = $orders[‘avg_price’];
conclusion
learn SQL
other things to consider
1. cache is a wonderful thing
2. * is not your friend
3. EXPLAIN/ANALYZE are
Questions?
Ad

Recommended

Developing applications for performance
Developing applications for performance
Leon Fayer
 
Database performance 101
Database performance 101
Leon Fayer
 
Wp query
Wp query
Savita Soni
 
テストデータどうしてますか?
テストデータどうしてますか?
Yuki Shibazaki
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)
Michael Schwern
 
How else can you write the code in PHP?
How else can you write the code in PHP?
Maksym Hopei
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
hannonhill
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
Alena Holligan
 
Php functions
Php functions
JIGAR MAKHIJA
 
Manage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShell
Chitexe Marcos Maniche
 
Perl6 grammars
Perl6 grammars
Andrew Shitov
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
Razvan Raducanu, PhD
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
l3rady
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
Neatly folding-a-tree
Neatly folding-a-tree
Workhorse Computing
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
Workhorse Computing
 
Intoduction to php restful web service
Intoduction to php restful web service
baabtra.com - No. 1 supplier of quality freshers
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Session8
Session8
สอนทำโปรเจคจบ วิทคอมไอทีคอมธุรกิจ
 
Getting Creative with WordPress Queries
Getting Creative with WordPress Queries
DrewAPicture
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Writing Maintainable Perl
Writing Maintainable Perl
tinypigdotcom
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
Fwdays
 
UNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 

More Related Content

What's hot (20)

[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
Alena Holligan
 
Php functions
Php functions
JIGAR MAKHIJA
 
Manage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShell
Chitexe Marcos Maniche
 
Perl6 grammars
Perl6 grammars
Andrew Shitov
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
Razvan Raducanu, PhD
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
l3rady
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
Neatly folding-a-tree
Neatly folding-a-tree
Workhorse Computing
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
Workhorse Computing
 
Intoduction to php restful web service
Intoduction to php restful web service
baabtra.com - No. 1 supplier of quality freshers
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Session8
Session8
สอนทำโปรเจคจบ วิทคอมไอทีคอมธุรกิจ
 
Getting Creative with WordPress Queries
Getting Creative with WordPress Queries
DrewAPicture
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Writing Maintainable Perl
Writing Maintainable Perl
tinypigdotcom
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
Fwdays
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
Alena Holligan
 
Manage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShell
Chitexe Marcos Maniche
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
Razvan Raducanu, PhD
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
l3rady
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
Workhorse Computing
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Getting Creative with WordPress Queries
Getting Creative with WordPress Queries
DrewAPicture
 
Introducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Writing Maintainable Perl
Writing Maintainable Perl
tinypigdotcom
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
Fwdays
 

Similar to PHP performance 101: so you need to use a database (20)

UNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
Chapter 3.1.pptx
Chapter 3.1.pptx
mebratu9
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php it's not (just) about the code
Beyond php it's not (just) about the code
Wim Godden
 
Object Relational Mapping in PHP
Object Relational Mapping in PHP
Rob Knight
 
Why Your Database Queries Stink -SeaGl.org November 11th, 2016
Why Your Database Queries Stink -SeaGl.org November 11th, 2016
Dave Stokes
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
John Coggeshall
 
Drupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
working with PHP & DB's
working with PHP & DB's
Hi-Tech College
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
Wim Godden
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
MySQL with PHP
MySQL with PHP
MsSJeyalakshmiVelsUn
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
3-Chapter-Edit.pptx debre tabour university
3-Chapter-Edit.pptx debre tabour university
alemunuruhak9
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
Steven Francia
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
Chapter 3.1.pptx
Chapter 3.1.pptx
mebratu9
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php it's not (just) about the code
Beyond php it's not (just) about the code
Wim Godden
 
Object Relational Mapping in PHP
Object Relational Mapping in PHP
Rob Knight
 
Why Your Database Queries Stink -SeaGl.org November 11th, 2016
Why Your Database Queries Stink -SeaGl.org November 11th, 2016
Dave Stokes
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
John Coggeshall
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
Wim Godden
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
3-Chapter-Edit.pptx debre tabour university
3-Chapter-Edit.pptx debre tabour university
alemunuruhak9
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
Steven Francia
 
Ad

More from Leon Fayer (12)

What kids can teach us about building effective teams
What kids can teach us about building effective teams
Leon Fayer
 
Как измерить успех
Как измерить успех
Leon Fayer
 
Bias in tech
Bias in tech
Leon Fayer
 
Building the right architecture for you
Building the right architecture for you
Leon Fayer
 
Lost art of troubleshooting
Lost art of troubleshooting
Leon Fayer
 
Adventures in public speaking
Adventures in public speaking
Leon Fayer
 
BizOps and you
BizOps and you
Leon Fayer
 
On call for developers
On call for developers
Leon Fayer
 
Production testing through monitoring
Production testing through monitoring
Leon Fayer
 
What DevOps is Not
What DevOps is Not
Leon Fayer
 
Breaking social dependency
Breaking social dependency
Leon Fayer
 
Improving DevOps through better monitoring
Improving DevOps through better monitoring
Leon Fayer
 
What kids can teach us about building effective teams
What kids can teach us about building effective teams
Leon Fayer
 
Как измерить успех
Как измерить успех
Leon Fayer
 
Building the right architecture for you
Building the right architecture for you
Leon Fayer
 
Lost art of troubleshooting
Lost art of troubleshooting
Leon Fayer
 
Adventures in public speaking
Adventures in public speaking
Leon Fayer
 
BizOps and you
BizOps and you
Leon Fayer
 
On call for developers
On call for developers
Leon Fayer
 
Production testing through monitoring
Production testing through monitoring
Leon Fayer
 
What DevOps is Not
What DevOps is Not
Leon Fayer
 
Breaking social dependency
Breaking social dependency
Leon Fayer
 
Improving DevOps through better monitoring
Improving DevOps through better monitoring
Leon Fayer
 
Ad

Recently uploaded (20)

Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 

PHP performance 101: so you need to use a database

  • 1. PHP Performance 101: so you need to use a database Leon Fayer @papa_fire
  • 2. Who am I ? • 20+ years development and operations of web applications • currently Vice President at OmniTI • can be found online: • @papa_fire • github:lfayer • http://fayerplay.com • https://joind.in/talk/view/11914
  • 3. what it is about databases & performance
  • 4. what it’s not about NoSQL MySQL
  • 5. how database connection works ① establish connection ② send query ③ process query ④ send result ⑤ close connection
  • 6. common database connection $dbh = new DB(…); $sth = $dbh->prepare($query); $sth->execute(); $result = $sth->fetchAll(); $dbh = null;
  • 7. common database connection ① var $dbh = new DB(…); ② var $sth = $dbh->prepare($query); ① $sth->execute(); ② var $result = $sth->fetchAll(); ③ $dbh = null;
  • 9. ① establish connection ⑤ close connection and
  • 13. short and helpful answer persistent connections avoid multiple connections
  • 14. how it works (high level) ① ① ① ⑤ ⑤ ⑤ ① ⑤
  • 15. conclusion reduce # of connections
  • 18. n+1 // get a list of items $sth = $dbh->prepare("select item_id from items where active = true"); $sth->execute(); $items = $sth->fetchAll(); // get properties for each items foreach ($items as $i) { $sth_prop = $dbh->prepare("select * from item_properties where item_id = ?"); $sth_prop->execute($item); $item_list[$i[‘item_id’]][‘props’] = $sth_prop->fetchAll(); $item_list[$i[‘item_id’]][‘id’] = $i[‘id’]; }
  • 19. n+1 you don’t know about // get a list of items $items = get_active_item_ids(); // get properties for each items foreach ($items as $i) { $item = Item->new($i[‘item_id’]) $item_list[$i[‘item_id’][‘id’] = $item->item_id; $item_list[$i[‘item_id’]][‘props’] = $item->properties(); }
  • 20. easy solution // get a list of items with properties $sth = $dbh->prepare("select i. item_id, p.* from items i, item_properties p where i.item_id = p.item_id and active = true"); $sth->execute(); $items = $sth->fetchAll(); // arrange object to your liking foreach ($items as $i) { $item_list[$i[‘item_id’]][‘props’] = $i; $item_list[$i[‘item_id’]][‘id’] = $i[‘id’]; }
  • 22. cool stuff :BONUS: Common Table Expressions (CTEs) * MySQL does not support CTEs
  • 23. // create temp table naughty_users // and get data from it with naughty_users as ( select * from users where banned = 1 ) select userid, email from naughty_users;
  • 24. even more cool Writeable Common Table Expressions * Postgres 9.1+ only
  • 25. multiple queries are required // create user record insert into users (name, email) values (?,?) returning userid // create address record insert into addresses (userid, address, city, state, zip) values (?,?,?,?,?) returning addressid // track changes to user information insert into user_history (userid, addressid, action) values (?,?,?) returning historyid
  • 26. or are they? with userdata as ( insert into users (name, email) values (?,?) returning userid ), addressdata as ( insert into addresses (userid, address, city, state, zip) select userid,?,?,?,? from userdata returning addressid ), historydata as ( insert into user_history (userid, addressid, action) select userid, addressid,? from userdata, addressdata returning historyid ) select userid, addressid, historyid from userdata, addressdata, historydata;
  • 27. why not use transactions? • no complicated transaction code • no complicated error handling code • reduced query overhead • better performance
  • 28. find out more For more details: http://omniti.com/seeds/writable-ctes-improve-performance
  • 31. why? 1. machine-generated 2. object construction overhead 3. false sense of control
  • 32. in one sentence you have no idea how it works
  • 36. may be shocking, but … databases can do math
  • 37. illustrating wrong // get all orders $sth = $dbh->prepare("select order_id, price from orders"); $sth->execute(); $orders= $sth->fetchAll(); //order by order_id usort($orders, function ($a, $b) { if ($a['order_id'] == $b['order_id']) { return 0; } return $a['order_id'] < $b['order_id'] ? -1 : 1; }); // get average $ for last 10 orders $count = 1; $total = 0; $avg = 0; foreach ($orders as $order) { $total += $order[‘price’]; if ($count == 10) { $avg = $total/$count; break 1; } $count++; }
  • 38. vs right // get average $ for last 10 orders $sth = $dbh->prepare("select avg(price) as avg_price from (select price from orders order by order_id desc limit 10) "); $sth->execute(); $orders= $sth->fetchAll(); $avg = $orders[‘avg_price’];
  • 40. other things to consider 1. cache is a wonderful thing 2. * is not your friend 3. EXPLAIN/ANALYZE are