SlideShare a Scribd company logo
Basic PHP
Database
programming
Hello!I am Dave Stokes
MySQl Community Manager
FORTRAN, Punch Cards, ‘Personal Home Page’, older than dirt, etc.
22 Years old!
MySQL 5.7 relased ~ 2 years ago
-- JSON Data Tyoe
MySQL 8 Developer Milestone
Release
-- Available for testing
-- Data dictionary
-- UTf8MB4
More Plug-in Features
-- Group replication
-- Document Store
Oracle MySQL Cloud
-- Enterprise edition of
software
1.
Basics
Client Server Model and simple
connections
Using MySQL
but concepts
will transpose
over to other
Relational
Database
Management
Systems.
● Network – tcp/ip
● Port 3306
● Windows, Mac, Linux,
& source code
+ containers
To connect you will need
0. Server name or IP address
1. Persmission to connect
2. Account/password
3. (more later)
<?php
$mysqli = new mysqli("127.0.0.1", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "n";
?>
<?php
$mysqli = new mysqli("127.0.0.1", "user", "password", "database");
Host – 127.0.0.1 (or 192.168.10.11 or db.foobar.com)
User – User on the MySQL server (mysql.user table), not OS user
Password – Clear text (other options later) -> Security issue
Database – Schema to be used. Can be selected/changed later
Port (optional) – defaults to 3306
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
If MySQL there is a MySQL connection error
then provide details
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
● Resource Guide
● Examples
● First place to look for answers
Syntax
Programming is hard but the syntactical aspects are
usually simple (some times too simple)
2.
Get Data
After connecting we need to do
something
1970’s
Disks are expensive and slow
Relational Model emerges with
goal of efficiency
Data Normaliation to berak
data in smaller logically
consistent groups
SQL was designed at IBM
to provide efficient
access to data via a
descriptive language
based on relational
calulus.
if ($result = $mysqli->query("SELECT * FROM City")) {
printf("Select returned %d rows.n", $result->num_rows);
/* free result set */
$result->close();
}
$mysqli->close();
?>
SELECT * FROM City
• * is a wild card for ‘all column in table
• City is the table being queried
• SELECT is the action (SELECT, UPDATE, DELETE, etc)
$mysqli = new mysqli();
$result = $mysqli->query();
Do Something with the data in app
$result->close();
$mysqli->close();
The basic flow is very
simple – connect,
query, close.
Note: the above is without return codes!
Always check return codes!
SELECT * FROM City
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)n", $row['id'], gettype($row['id']));
printf("label = %s (%s)n", $row['label'], gettype($row['label']));
$row = $result->fetch_assoc();
fetch_assoc -- Fetch a result row as an associative array
fetch_array() Fetch a result row as an associative, a numeric
array, or both
fetch_row() Get a result row as an enumerated array
fetch_object() Returns the current row of a result set as an
object
Congratulations! You know have the BASICS
down. The bad news is that there are are lot of
other things to learn.
The longest journey begins
with getting up off your
backside!!
3.
INput Data
Here is where being careful pays off
NEVER EVER TRUST
data input from a user!
Period!
EVER!
INTEGERS
Check to see if
intergers are really
integers by casting
them! Range check if
you can!!
STRINGS
Check size, filter out
junk, and expect the
unexpected!!
FILES
Isolate, scan, and
doublecheck.
Paranoia in defense of your data is a virtue not a sin
Yes, there are people out there that would love
to mess up your work, scramble or delete your
data, usurp your server, and in general treat you
professional life like a Games of Thrones plot
line including a Lannister but you are not a
Lannister
$QUERY = “SELECT * FROM PayingCustomers WERE userId = $id”;
if (!$mysqli->query($QUERY) {
echo “Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Can you spot TWO PROBLEMS with the above
(assume $email is from a form filled in by user) ?
What if $id is =
‘me@mw.com’ or 1 = 1
EVALUATES as TRUE
SELECT * FROM Users WHERE Name ="John Doe"
AND Pass ="Pass“
Name and Pass = " or ""="
SELECT * FROM Users WHERE Name ="" or ""=""
AND Pass ="" or ""=""
SELECT * FROM Users WHERE UserId = $UserId
$UserId = 15; DROP TABLE suppliers
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$id = 1;
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
for ($id = 2; $id < 5; $id++) {
if (!$stmt->execute()) {
echo "Execute failed:(" . $stmt->errno . ") " . $stmt-
>error;
}
}
4.
The dreaded N+1
Problem
Killing your database server
performance by a thousand cuts
Problem: You need a ride to work tomorrow and need to find an active
employee that lives in your city.
Query 1 – Find the active employees in your city.
Query 2 – Of those employees, find those who have a parking permit.
Versus
Query1 -- Find employees in your city that have a parking permit
Problem: You need to find all customers with unfulfilled orders over thirty days
that are not ready to ship and have already paid. A series of small queries is
doing to take more resources and time that one big query.
Each dive into the data has a cost – minimize!!
Let the database do the ‘heavy lifting’ – that is its purpose!
Every time you connect and send a query to a MySQL server it will check:
1. Is your computer allowed to connect?
2. Is your account/authentication-string valid?
3. Do you have permission to access the data requested?
This adds up with small queries
Whew!The is the basic basics!
1. SQL Anti Patterns:SQL Antipatterns: Avoiding the Pitfalls of Database Programming
Bill Karwin
2. Database Design and Relational Theory: Normal Forms and All That Jazz
CJ Date
THANKS!Any questions?
You can find me at @stoker or david.stokes @ oracle.com
Elephantdolphin.blogger.com
Slideshare.net/davidmstokes https://joind.in/talk/ad37a
Ad

Recommended

Php database connectivity
Php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
Dave Stokes
 
DBIx::Class walkthrough @ bangalore pm
DBIx::Class walkthrough @ bangalore pm
Sheeju Alex
 
Web2py
Web2py
Lucas D
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy Applications
Gabriela Ferrara
 
Using web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworks
Bruno Rocha
 
与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库
YUCHENG HU
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
Sanchit Raut
 
Php 2
Php 2
tnngo2
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Sequelize
Sequelize
Tarek Raihan
 
Coffeescript a z
Coffeescript a z
Starbuildr
 
DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009
Dirkjan Bussink
 
Object oriented mysqli connection function
Object oriented mysqli connection function
clickon2010
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016
Colin O'Dell
 
Web2py Code Lab
Web2py Code Lab
Colin Su
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a database
Leon Fayer
 
Developing applications for performance
Developing applications for performance
Leon Fayer
 
Couchdb
Couchdb
Brian Smith
 
Rails 3 ActiveRecord
Rails 3 ActiveRecord
Blazing Cloud
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 
Jqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
DrewAPicture
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
hannonhill
 
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
Jose Luis Martínez
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
Amanda Gilmore
 
Download It
Download It
webhostingguy
 
lecture 7 - Introduction to MySQL with PHP.pptx
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 

More Related Content

What's hot (20)

Php 2
Php 2
tnngo2
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Sequelize
Sequelize
Tarek Raihan
 
Coffeescript a z
Coffeescript a z
Starbuildr
 
DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009
Dirkjan Bussink
 
Object oriented mysqli connection function
Object oriented mysqli connection function
clickon2010
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016
Colin O'Dell
 
Web2py Code Lab
Web2py Code Lab
Colin Su
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a database
Leon Fayer
 
Developing applications for performance
Developing applications for performance
Leon Fayer
 
Couchdb
Couchdb
Brian Smith
 
Rails 3 ActiveRecord
Rails 3 ActiveRecord
Blazing Cloud
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 
Jqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
DrewAPicture
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
hannonhill
 
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
Jose Luis Martínez
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
Amanda Gilmore
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway
 
Coffeescript a z
Coffeescript a z
Starbuildr
 
DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009
Dirkjan Bussink
 
Object oriented mysqli connection function
Object oriented mysqli connection function
clickon2010
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016
Colin O'Dell
 
Web2py Code Lab
Web2py Code Lab
Colin Su
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a database
Leon Fayer
 
Developing applications for performance
Developing applications for performance
Leon Fayer
 
Rails 3 ActiveRecord
Rails 3 ActiveRecord
Blazing Cloud
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 
Jqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
DrewAPicture
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
hannonhill
 
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
MooseX::Datamodel - Barcelona Perl Workshop Lightning talk
Jose Luis Martínez
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
Amanda Gilmore
 

Similar to PHP Database Programming Basics -- Northeast PHP (20)

Download It
Download It
webhostingguy
 
lecture 7 - Introduction to MySQL with PHP.pptx
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
3-Chapter-Edit.pptx debre tabour university
3-Chapter-Edit.pptx debre tabour university
alemunuruhak9
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
Php summary
Php summary
Michelle Darling
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Php modul-3
Php modul-3
Kristophorus Hadiono
 
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
 
3 php-connect-to-my sql
3 php-connect-to-my sql
Achchuthan Yogarajah
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
John Coggeshall
 
Php My Sql Security 2007
Php My Sql Security 2007
Aung Khant
 
Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PHP with MySQL
PHP with MySQL
wahidullah mudaser
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
MySQL with PHP
MySQL with PHP
MsSJeyalakshmiVelsUn
 
Synapse india reviews on php and sql
Synapse india reviews on php and sql
saritasingh19866
 
Five Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo Vancouver
Dave Stokes
 
Php and database functionality
Php and database functionality
Sayed Ahmed
 
lecture 7 - Introduction to MySQL with PHP.pptx
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
3-Chapter-Edit.pptx debre tabour university
3-Chapter-Edit.pptx debre tabour university
alemunuruhak9
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
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
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
John Coggeshall
 
Php My Sql Security 2007
Php My Sql Security 2007
Aung Khant
 
Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
Synapse india reviews on php and sql
Synapse india reviews on php and sql
saritasingh19866
 
Five Database Mistakes and how to fix them -- Confoo Vancouver
Five Database Mistakes and how to fix them -- Confoo Vancouver
Dave Stokes
 
Php and database functionality
Php and database functionality
Sayed Ahmed
 
Ad

More from Dave Stokes (20)

Valkey 101 - SCaLE 22x March 2025 Stokes.pdf
Valkey 101 - SCaLE 22x March 2025 Stokes.pdf
Dave Stokes
 
Locking Down Your MySQL Database.pptx
Locking Down Your MySQL Database.pptx
Dave Stokes
 
Linuxfest Northwest 2022 - MySQL 8.0 Nre Features
Linuxfest Northwest 2022 - MySQL 8.0 Nre Features
Dave Stokes
 
MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022
Dave Stokes
 
MySQL 8.0 Features -- Oracle CodeOne 2019, All Things Open 2019
MySQL 8.0 Features -- Oracle CodeOne 2019, All Things Open 2019
Dave Stokes
 
Windowing Functions - Little Rock Tech fest 2019
Windowing Functions - Little Rock Tech fest 2019
Dave Stokes
 
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
Dave Stokes
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPI
Dave Stokes
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
Dave Stokes
 
The Proper Care and Feeding of MySQL Databases
The Proper Care and Feeding of MySQL Databases
Dave Stokes
 
MySQL without the SQL -- Cascadia PHP
MySQL without the SQL -- Cascadia PHP
Dave Stokes
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
Dave Stokes
 
MySQL Without The SQL -- Oh My! PHP[Tek] June 2018
MySQL Without The SQL -- Oh My! PHP[Tek] June 2018
Dave Stokes
 
Presentation Skills for Open Source Folks
Presentation Skills for Open Source Folks
Dave Stokes
 
MySQL Without the SQL -- Oh My! Longhorn PHP Conference
MySQL Without the SQL -- Oh My! Longhorn PHP Conference
Dave Stokes
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
Dave Stokes
 
ConFoo MySQL Replication Evolution : From Simple to Group Replication
ConFoo MySQL Replication Evolution : From Simple to Group Replication
Dave Stokes
 
Advanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
Dave Stokes
 
Making MySQL Agile-ish
Making MySQL Agile-ish
Dave Stokes
 
MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017
Dave Stokes
 
Valkey 101 - SCaLE 22x March 2025 Stokes.pdf
Valkey 101 - SCaLE 22x March 2025 Stokes.pdf
Dave Stokes
 
Locking Down Your MySQL Database.pptx
Locking Down Your MySQL Database.pptx
Dave Stokes
 
Linuxfest Northwest 2022 - MySQL 8.0 Nre Features
Linuxfest Northwest 2022 - MySQL 8.0 Nre Features
Dave Stokes
 
MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022
Dave Stokes
 
MySQL 8.0 Features -- Oracle CodeOne 2019, All Things Open 2019
MySQL 8.0 Features -- Oracle CodeOne 2019, All Things Open 2019
Dave Stokes
 
Windowing Functions - Little Rock Tech fest 2019
Windowing Functions - Little Rock Tech fest 2019
Dave Stokes
 
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
Dave Stokes
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPI
Dave Stokes
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
Dave Stokes
 
The Proper Care and Feeding of MySQL Databases
The Proper Care and Feeding of MySQL Databases
Dave Stokes
 
MySQL without the SQL -- Cascadia PHP
MySQL without the SQL -- Cascadia PHP
Dave Stokes
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
Dave Stokes
 
MySQL Without The SQL -- Oh My! PHP[Tek] June 2018
MySQL Without The SQL -- Oh My! PHP[Tek] June 2018
Dave Stokes
 
Presentation Skills for Open Source Folks
Presentation Skills for Open Source Folks
Dave Stokes
 
MySQL Without the SQL -- Oh My! Longhorn PHP Conference
MySQL Without the SQL -- Oh My! Longhorn PHP Conference
Dave Stokes
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
Dave Stokes
 
ConFoo MySQL Replication Evolution : From Simple to Group Replication
ConFoo MySQL Replication Evolution : From Simple to Group Replication
Dave Stokes
 
Advanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
Dave Stokes
 
Making MySQL Agile-ish
Making MySQL Agile-ish
Dave Stokes
 
MySQL 101 PHPTek 2017
MySQL 101 PHPTek 2017
Dave Stokes
 
Ad

Recently uploaded (20)

inside the internet - understanding the TCP/IP protocol
inside the internet - understanding the TCP/IP protocol
shainweniton02
 
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
The ARUBA Kind of new Proposal Umum .pptx
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
Global Networking Trends, presented at the India ISP Conclave 2025
Global Networking Trends, presented at the India ISP Conclave 2025
APNIC
 
原版澳洲斯文本科技大学毕业证(SUT毕业证书)如何办理
原版澳洲斯文本科技大学毕业证(SUT毕业证书)如何办理
taqyed
 
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
Transmission Control Protocol (TCP) and Starlink
Transmission Control Protocol (TCP) and Starlink
APNIC
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
ChatGPT_and_Its_Uses_Presentationss.pptx
ChatGPT_and_Its_Uses_Presentationss.pptx
Neha Prakash
 
BASICS OF SAP _ ALL ABOUT SAP _WHY SAP OVER ANY OTHER ERP SYSTEM
BASICS OF SAP _ ALL ABOUT SAP _WHY SAP OVER ANY OTHER ERP SYSTEM
AhmadAli716831
 
Almos Entirely Correct Mixing with Apps to Voting
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 
最新版美国特拉华大学毕业证(UDel毕业证书)原版定制
最新版美国特拉华大学毕业证(UDel毕业证书)原版定制
taqyea
 
BroadLink Cloud Service introduction.pdf
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
DDoS in India, presented at INNOG 8 by Dave Phelan
DDoS in India, presented at INNOG 8 by Dave Phelan
APNIC
 
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
AhmadAli716831
 
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
ChatGPT A.I. Powered Chatbot and Popularization.pdf
ChatGPT A.I. Powered Chatbot and Popularization.pdf
StanleySamson1
 
Pitch PitchPitchPitchPitchPitchPitch.pptx
Pitch PitchPitchPitchPitchPitchPitch.pptx
157551
 
TCP/IP presentation SET2- Information Systems
TCP/IP presentation SET2- Information Systems
agnesegtcagliero
 
Make DDoS expensive for the threat actors
Make DDoS expensive for the threat actors
APNIC
 
inside the internet - understanding the TCP/IP protocol
inside the internet - understanding the TCP/IP protocol
shainweniton02
 
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
The ARUBA Kind of new Proposal Umum .pptx
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
Global Networking Trends, presented at the India ISP Conclave 2025
Global Networking Trends, presented at the India ISP Conclave 2025
APNIC
 
原版澳洲斯文本科技大学毕业证(SUT毕业证书)如何办理
原版澳洲斯文本科技大学毕业证(SUT毕业证书)如何办理
taqyed
 
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
Transmission Control Protocol (TCP) and Starlink
Transmission Control Protocol (TCP) and Starlink
APNIC
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
ChatGPT_and_Its_Uses_Presentationss.pptx
ChatGPT_and_Its_Uses_Presentationss.pptx
Neha Prakash
 
BASICS OF SAP _ ALL ABOUT SAP _WHY SAP OVER ANY OTHER ERP SYSTEM
BASICS OF SAP _ ALL ABOUT SAP _WHY SAP OVER ANY OTHER ERP SYSTEM
AhmadAli716831
 
Almos Entirely Correct Mixing with Apps to Voting
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 
最新版美国特拉华大学毕业证(UDel毕业证书)原版定制
最新版美国特拉华大学毕业证(UDel毕业证书)原版定制
taqyea
 
BroadLink Cloud Service introduction.pdf
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
DDoS in India, presented at INNOG 8 by Dave Phelan
DDoS in India, presented at INNOG 8 by Dave Phelan
APNIC
 
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
AhmadAli716831
 
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
ChatGPT A.I. Powered Chatbot and Popularization.pdf
ChatGPT A.I. Powered Chatbot and Popularization.pdf
StanleySamson1
 
Pitch PitchPitchPitchPitchPitchPitch.pptx
Pitch PitchPitchPitchPitchPitchPitch.pptx
157551
 
TCP/IP presentation SET2- Information Systems
TCP/IP presentation SET2- Information Systems
agnesegtcagliero
 
Make DDoS expensive for the threat actors
Make DDoS expensive for the threat actors
APNIC
 

PHP Database Programming Basics -- Northeast PHP

  • 2. Hello!I am Dave Stokes MySQl Community Manager FORTRAN, Punch Cards, ‘Personal Home Page’, older than dirt, etc.
  • 3. 22 Years old! MySQL 5.7 relased ~ 2 years ago -- JSON Data Tyoe MySQL 8 Developer Milestone Release -- Available for testing -- Data dictionary -- UTf8MB4 More Plug-in Features -- Group replication -- Document Store Oracle MySQL Cloud -- Enterprise edition of software
  • 4. 1. Basics Client Server Model and simple connections Using MySQL but concepts will transpose over to other Relational Database Management Systems.
  • 5. ● Network – tcp/ip ● Port 3306 ● Windows, Mac, Linux, & source code + containers
  • 6. To connect you will need 0. Server name or IP address 1. Persmission to connect 2. Account/password 3. (more later)
  • 7. <?php $mysqli = new mysqli("127.0.0.1", "user", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } echo $mysqli->host_info . "n"; ?>
  • 8. <?php $mysqli = new mysqli("127.0.0.1", "user", "password", "database"); Host – 127.0.0.1 (or 192.168.10.11 or db.foobar.com) User – User on the MySQL server (mysql.user table), not OS user Password – Clear text (other options later) -> Security issue Database – Schema to be used. Can be selected/changed later Port (optional) – defaults to 3306
  • 9. if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } If MySQL there is a MySQL connection error then provide details
  • 10. <?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
  • 11. ● Resource Guide ● Examples ● First place to look for answers
  • 12. Syntax Programming is hard but the syntactical aspects are usually simple (some times too simple)
  • 13. 2. Get Data After connecting we need to do something
  • 14. 1970’s Disks are expensive and slow Relational Model emerges with goal of efficiency Data Normaliation to berak data in smaller logically consistent groups SQL was designed at IBM to provide efficient access to data via a descriptive language based on relational calulus.
  • 15. if ($result = $mysqli->query("SELECT * FROM City")) { printf("Select returned %d rows.n", $result->num_rows); /* free result set */ $result->close(); } $mysqli->close(); ?>
  • 16. SELECT * FROM City • * is a wild card for ‘all column in table • City is the table being queried • SELECT is the action (SELECT, UPDATE, DELETE, etc)
  • 17. $mysqli = new mysqli(); $result = $mysqli->query(); Do Something with the data in app $result->close(); $mysqli->close(); The basic flow is very simple – connect, query, close. Note: the above is without return codes! Always check return codes!
  • 18. SELECT * FROM City $result = $mysqli->query("SELECT id, label FROM test WHERE id = 1"); $row = $result->fetch_assoc(); printf("id = %s (%s)n", $row['id'], gettype($row['id'])); printf("label = %s (%s)n", $row['label'], gettype($row['label']));
  • 19. $row = $result->fetch_assoc(); fetch_assoc -- Fetch a result row as an associative array fetch_array() Fetch a result row as an associative, a numeric array, or both fetch_row() Get a result row as an enumerated array fetch_object() Returns the current row of a result set as an object
  • 20. Congratulations! You know have the BASICS down. The bad news is that there are are lot of other things to learn.
  • 21. The longest journey begins with getting up off your backside!!
  • 22. 3. INput Data Here is where being careful pays off
  • 23. NEVER EVER TRUST data input from a user! Period! EVER!
  • 24. INTEGERS Check to see if intergers are really integers by casting them! Range check if you can!! STRINGS Check size, filter out junk, and expect the unexpected!! FILES Isolate, scan, and doublecheck. Paranoia in defense of your data is a virtue not a sin
  • 25. Yes, there are people out there that would love to mess up your work, scramble or delete your data, usurp your server, and in general treat you professional life like a Games of Thrones plot line including a Lannister but you are not a Lannister
  • 26. $QUERY = “SELECT * FROM PayingCustomers WERE userId = $id”; if (!$mysqli->query($QUERY) { echo “Query failed: (" . $mysqli->errno . ") " . $mysqli->error; } Can you spot TWO PROBLEMS with the above (assume $email is from a form filled in by user) ?
  • 27. What if $id is = ‘[email protected]’ or 1 = 1 EVALUATES as TRUE
  • 28. SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="Pass“ Name and Pass = " or ""=" SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
  • 29. SELECT * FROM Users WHERE UserId = $UserId $UserId = 15; DROP TABLE suppliers
  • 30. if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) { echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; } $id = 1; if (!$stmt->bind_param("i", $id)) { echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; } if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; }
  • 31. for ($id = 2; $id < 5; $id++) { if (!$stmt->execute()) { echo "Execute failed:(" . $stmt->errno . ") " . $stmt- >error; } }
  • 32. 4. The dreaded N+1 Problem Killing your database server performance by a thousand cuts
  • 33. Problem: You need a ride to work tomorrow and need to find an active employee that lives in your city. Query 1 – Find the active employees in your city. Query 2 – Of those employees, find those who have a parking permit. Versus Query1 -- Find employees in your city that have a parking permit
  • 34. Problem: You need to find all customers with unfulfilled orders over thirty days that are not ready to ship and have already paid. A series of small queries is doing to take more resources and time that one big query. Each dive into the data has a cost – minimize!! Let the database do the ‘heavy lifting’ – that is its purpose!
  • 35. Every time you connect and send a query to a MySQL server it will check: 1. Is your computer allowed to connect? 2. Is your account/authentication-string valid? 3. Do you have permission to access the data requested? This adds up with small queries
  • 36. Whew!The is the basic basics!
  • 37. 1. SQL Anti Patterns:SQL Antipatterns: Avoiding the Pitfalls of Database Programming Bill Karwin 2. Database Design and Relational Theory: Normal Forms and All That Jazz CJ Date
  • 38. THANKS!Any questions? You can find me at @stoker or david.stokes @ oracle.com Elephantdolphin.blogger.com Slideshare.net/davidmstokes https://joind.in/talk/ad37a