SlideShare a Scribd company logo
PDO – PHP DATABASE EXTENSION
PDO (PHP Data Objects) is a PHP extension through which we can access
and work with databases. Though PDO is similar in many aspects to
mySQLi, it is better to work with for the following reasons:
• It is better protected against hackers.
• It is consistent across databases, so it can work with MySQL as well as
other types of databases (SQLite, Oracle, PostgreSQL, etc.)
• It is object oriented at its core.
In this PDO tutorial you will find recipes for 4 basic functions that we
perform with the database: insertion, selection, update, and deletion. The
recipes are intended to work with MySQL, but we can easily switch it with
another database.
How to connect with the database through PDO?
It is considered good practice to wrap the database connection within a try-
catch block so that, if anything goes wrong, an exception will be thrown.
We can customize the error message but, in order to keep things simple,
we’ll settle with the error message that PDO provides.
In order to connect to the database, we’ll need the database name, username,
and password.
/ DB credentials.
define('DB_HOST','localhost');
define('DB_USER','your user name');
define('DB_PASS','your user password');
define('DB_NAME','your database name');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,
DB_USER, DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
How to close the database connection?
PHP automatically closes the database connection but, if the need arises, we
can deliberately close the connection with the following line of code:
$dbh = null;
How to use PDO to insert data into the database?
The SQL code for the users table:
3
4
5
6
7
CREATE TABLE IF NOT EXISTS users (id int(11) NOT NULL
AUTO_INCREMENT,
name varchar(60) DEFAULT NULL,
phone varchar(12) DEFAULT NULL,
city varchar(60) DEFAULT NULL,
date_added date DEFAULT NULL,
PRIMARY KEY (id)
)
1) Write a regular SQL query but, instead of values, put named placeholders.
For example:
1
2
$sql = "INSERT INTO `users`(`name`, `phone`, `city`, `date_added`)
VALUES(:name,:phone,:city,:date)";
The use of placeholders is known as prepared statements. We use prepared statements
as templates that we can fill later on with actual values.
2) Prepare the query:
$query = $dbh -> prepare($sql);
3) Bind the placeholders to the variables:
$query->bindParam(':name',$name);
You can add a third parameter which filters the data before it reaches the database:
$query->bindParam(':name',$name,PDO::PARAM_STR);
$query->bindParam(':phone',$phone,PDO::PARAM_INT);
$query->bindParam(':city',$city,PDO::PARAM_STR);
$query->bindParam(':date',$date,PDO::PARAM_STR);
PDO::PARAM_STR is used for strings.
PDO::PARAM_INT is used for integers.
PDO::PARAM_BOOL allows only boolean (true/false) values.
PDO::PARAM_NULL allows only NULL datatype.
4) Assign the values to the variables.
$name = "Anuj kumar";
$phone = "944324238";
$city = "New Delhi";
$date = date('Y-m-d');
5) Execute the query:
1 $query -> execute();
6) Check that the insertion really worked:
$lastInsertId = $dbh->lastInsertId();
if($lastInsertId>0)
{
echo "OK";
}
else
{
echo "not OK";
}
All code together now:
 $sql = "INSERT INTO `users`
 (`name`, `phone`, `city`, `date_added`)
 VALUES
 (:name,:phone,:city,:date)";
 $query = $dbh -> prepare($sql);
 $query->bindParam(':name',$name,PDO::PARAM_STR);
 $query->bindParam(':phone',$phone,PDO::PARAM_INT);
 $query->bindParam(':city',$city,PDO::PARAM_STR);
 $query->bindParam(':date',$date);
 // Insert the first row
 $name = "Anuj";
 $phone = "1231234567";
 $city = "New Delhi";
 $date = date('Y-m-d');
 $query -> execute();
 $lastInsertId = $dbh->lastInsertId();
 if($lastInsertId>0)
 {
 echo "OK";
 }
 else {
 echo "not OK"; }

More Related Content

What's hot (20)

Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with Flysystem
Frank de Jonge
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
DataminingTools Inc
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPIDevelop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPI
Dave Stokes
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
Dave Stokes
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
Jalpesh Vasa
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San FranciscoMySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
Dave Stokes
 
MySQL
MySQLMySQL
MySQL
Gouthaman V
 
lab56_db
lab56_dblab56_db
lab56_db
tutorialsruby
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
Nakka Srilakshmi
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
jeromevdl
 
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
Firdaus Adib
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
Introducing FSter
Introducing FSterIntroducing FSter
Introducing FSter
itsmesrl
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQL
Norvald Ryeng
 
Persistences
PersistencesPersistences
Persistences
Training Guide
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
Knoldus Inc.
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
wali1195189
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
MingHo Chang
 
Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with Flysystem
Frank de Jonge
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPIDevelop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPI
Dave Stokes
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
Dave Stokes
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San FranciscoMySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
Dave Stokes
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
jeromevdl
 
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
Firdaus Adib
 
Introducing FSter
Introducing FSterIntroducing FSter
Introducing FSter
itsmesrl
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQL
Norvald Ryeng
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
Knoldus Inc.
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
wali1195189
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
MingHo Chang
 

Similar to Pdo – php database extension-Phpgurukul (20)

PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
andrewdotcom
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
Mohammad Imam Hossain
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
Rengga Aditya
 
Php talk
Php talkPhp talk
Php talk
Jamil Ramsey
 
download presentation
download presentationdownload presentation
download presentation
webhostingguy
 
php databse handling
php databse handlingphp databse handling
php databse handling
kunj desai
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
hiren.joshi
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
AJINKYA N
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
Valentine Dianov
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
NidiaRamirez07
 
SQL Prepared Statements Tutorial
SQL Prepared Statements TutorialSQL Prepared Statements Tutorial
SQL Prepared Statements Tutorial
ProdigyView
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Php summary
Php summaryPhp summary
Php summary
Michelle Darling
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7
Muhammad Hafiz Hasan
 
PHP - PDO.pdf
PHP - PDO.pdfPHP - PDO.pdf
PHP - PDO.pdf
ssuser1e29f11
 
This slide show will brief about database handling
This slide show will brief about database handlingThis slide show will brief about database handling
This slide show will brief about database handling
averynight005
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
Hi-Tech College
 
PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
andrewdotcom
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
download presentation
download presentationdownload presentation
download presentation
webhostingguy
 
php databse handling
php databse handlingphp databse handling
php databse handling
kunj desai
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
hiren.joshi
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
AJINKYA N
 
SQL Prepared Statements Tutorial
SQL Prepared Statements TutorialSQL Prepared Statements Tutorial
SQL Prepared Statements Tutorial
ProdigyView
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
This slide show will brief about database handling
This slide show will brief about database handlingThis slide show will brief about database handling
This slide show will brief about database handling
averynight005
 
Ad

Recently uploaded (20)

Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
ManiMaran230751
 
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdfISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Air Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdfAir Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Application Security and Secure Software Development Lifecycle
Application  Security and Secure Software Development LifecycleApplication  Security and Secure Software Development Lifecycle
Application Security and Secure Software Development Lifecycle
DrKavithaP1
 
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning ModelEnhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
IRJET Journal
 
All about the Snail Power Catalog Product 2025
All about the Snail Power Catalog  Product 2025All about the Snail Power Catalog  Product 2025
All about the Snail Power Catalog Product 2025
kstgroupvn
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
Introduction of Structural Audit and Health Montoring.pptx
Introduction of Structural Audit and Health Montoring.pptxIntroduction of Structural Audit and Health Montoring.pptx
Introduction of Structural Audit and Health Montoring.pptx
gunjalsachin
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 / HIFLUX Co., Ltd.
 
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete ColumnsAxial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Journal of Soft Computing in Civil Engineering
 
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdfKevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Medicoz Clinic
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdfISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdfSoftware_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
VanshMunjal7
 
Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
Forensic Science – Digital Forensics – Digital Evidence – The Digital Forensi...
ManiMaran230751
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Application Security and Secure Software Development Lifecycle
Application  Security and Secure Software Development LifecycleApplication  Security and Secure Software Development Lifecycle
Application Security and Secure Software Development Lifecycle
DrKavithaP1
 
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning ModelEnhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
IRJET Journal
 
All about the Snail Power Catalog Product 2025
All about the Snail Power Catalog  Product 2025All about the Snail Power Catalog  Product 2025
All about the Snail Power Catalog Product 2025
kstgroupvn
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
Introduction of Structural Audit and Health Montoring.pptx
Introduction of Structural Audit and Health Montoring.pptxIntroduction of Structural Audit and Health Montoring.pptx
Introduction of Structural Audit and Health Montoring.pptx
gunjalsachin
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 / HIFLUX Co., Ltd.
 
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdfKevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Kevin Corke Spouse Revealed A Deep Dive Into His Private Life.pdf
Medicoz Clinic
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdfSoftware_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
VanshMunjal7
 
Ad

Pdo – php database extension-Phpgurukul

  • 1. PDO – PHP DATABASE EXTENSION PDO (PHP Data Objects) is a PHP extension through which we can access and work with databases. Though PDO is similar in many aspects to mySQLi, it is better to work with for the following reasons: • It is better protected against hackers. • It is consistent across databases, so it can work with MySQL as well as other types of databases (SQLite, Oracle, PostgreSQL, etc.) • It is object oriented at its core. In this PDO tutorial you will find recipes for 4 basic functions that we perform with the database: insertion, selection, update, and deletion. The recipes are intended to work with MySQL, but we can easily switch it with another database. How to connect with the database through PDO? It is considered good practice to wrap the database connection within a try- catch block so that, if anything goes wrong, an exception will be thrown. We can customize the error message but, in order to keep things simple, we’ll settle with the error message that PDO provides.
  • 2. In order to connect to the database, we’ll need the database name, username, and password. / DB credentials. define('DB_HOST','localhost'); define('DB_USER','your user name'); define('DB_PASS','your user password'); define('DB_NAME','your database name'); // Establish database connection. try { $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")); } catch (PDOException $e) { exit("Error: " . $e->getMessage()); }
  • 3. How to close the database connection? PHP automatically closes the database connection but, if the need arises, we can deliberately close the connection with the following line of code: $dbh = null; How to use PDO to insert data into the database? The SQL code for the users table: 3 4 5 6 7 CREATE TABLE IF NOT EXISTS users (id int(11) NOT NULL AUTO_INCREMENT, name varchar(60) DEFAULT NULL, phone varchar(12) DEFAULT NULL, city varchar(60) DEFAULT NULL, date_added date DEFAULT NULL, PRIMARY KEY (id) )
  • 4. 1) Write a regular SQL query but, instead of values, put named placeholders. For example: 1 2 $sql = "INSERT INTO `users`(`name`, `phone`, `city`, `date_added`) VALUES(:name,:phone,:city,:date)"; The use of placeholders is known as prepared statements. We use prepared statements as templates that we can fill later on with actual values. 2) Prepare the query: $query = $dbh -> prepare($sql); 3) Bind the placeholders to the variables: $query->bindParam(':name',$name); You can add a third parameter which filters the data before it reaches the database: $query->bindParam(':name',$name,PDO::PARAM_STR); $query->bindParam(':phone',$phone,PDO::PARAM_INT); $query->bindParam(':city',$city,PDO::PARAM_STR); $query->bindParam(':date',$date,PDO::PARAM_STR); PDO::PARAM_STR is used for strings. PDO::PARAM_INT is used for integers. PDO::PARAM_BOOL allows only boolean (true/false) values. PDO::PARAM_NULL allows only NULL datatype.
  • 5. 4) Assign the values to the variables. $name = "Anuj kumar"; $phone = "944324238"; $city = "New Delhi"; $date = date('Y-m-d'); 5) Execute the query: 1 $query -> execute(); 6) Check that the insertion really worked: $lastInsertId = $dbh->lastInsertId(); if($lastInsertId>0) { echo "OK"; } else { echo "not OK"; }
  • 6. All code together now:  $sql = "INSERT INTO `users`  (`name`, `phone`, `city`, `date_added`)  VALUES  (:name,:phone,:city,:date)";  $query = $dbh -> prepare($sql);  $query->bindParam(':name',$name,PDO::PARAM_STR);  $query->bindParam(':phone',$phone,PDO::PARAM_INT);  $query->bindParam(':city',$city,PDO::PARAM_STR);  $query->bindParam(':date',$date);  // Insert the first row  $name = "Anuj";  $phone = "1231234567";  $city = "New Delhi";  $date = date('Y-m-d');  $query -> execute();  $lastInsertId = $dbh->lastInsertId();  if($lastInsertId>0)  {  echo "OK";  }  else {  echo "not OK"; }