SlideShare une entreprise Scribd logo
1  sur  6
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"; }

Contenu connexe

Tendances

Introducing FSter
Introducing FSterIntroducing FSter
Introducing FSter
itsmesrl
 

Tendances (20)

Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with Flysystem
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 
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
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
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
 
MySQL
MySQLMySQL
MySQL
 
lab56_db
lab56_dblab56_db
lab56_db
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
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
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
Introducing FSter
Introducing FSterIntroducing FSter
Introducing FSter
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQL
 
Persistences
PersistencesPersistences
Persistences
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
 

Similaire à Pdo – php database extension-Phpgurukul

Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
Vineet Kumar Saini
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
hiren.joshi
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
Katie Gulley
 

Similaire à Pdo – php database extension-Phpgurukul (20)

Mysql DBI
Mysql DBIMysql DBI
Mysql DBI
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
 
Sa
SaSa
Sa
 
Slick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon LondonSlick Data Sharding: Slides from DrupalCon London
Slick Data Sharding: Slides from DrupalCon London
 
php databse handling
php databse handlingphp databse handling
php databse handling
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
 
Sql
SqlSql
Sql
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Sq linjection
Sq linjectionSq linjection
Sq linjection
 
MySQL with PHP
MySQL with PHPMySQL with PHP
MySQL with PHP
 
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
Php & my sql  - how do pdo, mysq-li, and x devapi do what they doPhp & my sql  - how do pdo, mysq-li, and x devapi do what they do
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
 
Quiz With Answers Drupal
Quiz With  Answers  DrupalQuiz With  Answers  Drupal
Quiz With Answers Drupal
 

Dernier

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Dernier (20)

The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 

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