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

ODP
PHP Data Objects
PPTX
Mdst 3559-03-01-sql-php
ODP
Adodb Pdo Presentation
PPT
MYSQL - PHP Database Connectivity
PDF
MySQL without the SQL -- Cascadia PHP
PPT
Database presentation
PPTX
Mysql
PDF
Introduction to php database connectivity
PHP Data Objects
Mdst 3559-03-01-sql-php
Adodb Pdo Presentation
MYSQL - PHP Database Connectivity
MySQL without the SQL -- Cascadia PHP
Database presentation
Mysql
Introduction to php database connectivity

What's hot (20)

PDF
Filesystem Abstraction with Flysystem
PPTX
MySql:Basics
PPTX
Develop PHP Applications with MySQL X DevAPI
PPTX
Database Connectivity in PHP
PDF
MySQL 8 Server Optimization Swanseacon 2018
PDF
4.3 MySQL + PHP
PDF
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
PPT
PDF
lab56_db
PPT
Php with MYSQL Database
PPTX
Android Data Storagefinal
PDF
Softshake - Offline applications
PPT
PHP - Getting good with MySQL part II
PDF
MySQL for beginners
PDF
Introducing FSter
PDF
JSON Array Indexes in MySQL
PPT
Persistences
PDF
Brief introduction of Slick
PPTX
MS SQL Database basic
PDF
Android - Data Storage
Filesystem Abstraction with Flysystem
MySql:Basics
Develop PHP Applications with MySQL X DevAPI
Database Connectivity in PHP
MySQL 8 Server Optimization Swanseacon 2018
4.3 MySQL + PHP
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
lab56_db
Php with MYSQL Database
Android Data Storagefinal
Softshake - Offline applications
PHP - Getting good with MySQL part II
MySQL for beginners
Introducing FSter
JSON Array Indexes in MySQL
Persistences
Brief introduction of Slick
MS SQL Database basic
Android - Data Storage
Ad

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

PPT
Mysql DBI
PDF
Top 100 PHP Interview Questions and Answers
ODP
Codebits 2012 - Fast relational web site construction.
PPT
Php Data Objects
PPT
Slick Data Sharding: Slides from DrupalCon London
PPT
php databse handling
PPT
Introducing PHP Data Objects
PPT
Working with databases in Perl
PPT
Migrating from PHP 4 to PHP 5
PDF
DOCX
Php interview questions
PDF
Service discovery and configuration provisioning
PPTX
Connecting to my sql using PHP
PPTX
PDF
Questions On The Code And Core Module
PPTX
MySQL with PHP
PDF
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
DOC
Quiz With Answers Drupal
Mysql DBI
Top 100 PHP Interview Questions and Answers
Codebits 2012 - Fast relational web site construction.
Php Data Objects
Slick Data Sharding: Slides from DrupalCon London
php databse handling
Introducing PHP Data Objects
Working with databases in Perl
Migrating from PHP 4 to PHP 5
Php interview questions
Service discovery and configuration provisioning
Connecting to my sql using PHP
Questions On The Code And Core Module
MySQL with PHP
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
Quiz With Answers Drupal
Ad

Recently uploaded (20)

PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
436813905-LNG-Process-Overview-Short.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
PDF
composite construction of structures.pdf
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Road Safety tips for School Kids by a k maurya.pptx
PDF
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
PPTX
AgentX UiPath Community Webinar series - Delhi
PDF
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
PDF
Structs to JSON How Go Powers REST APIs.pdf
Lesson 3_Tessellation.pptx finite Mathematics
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
436813905-LNG-Process-Overview-Short.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
composite construction of structures.pdf
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
bas. eng. economics group 4 presentation 1.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Road Safety tips for School Kids by a k maurya.pptx
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
AgentX UiPath Community Webinar series - Delhi
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
Structs to JSON How Go Powers REST APIs.pdf

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"; }