SlideShare ist ein Scribd-Unternehmen logo
1 von 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"; }

Weitere ähnliche Inhalte

Was ist angesagt?

Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFrank 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 DevAPIDave Stokes
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018Dave 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 FranciscoDave Stokes
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
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 IIFirdaus Adib
 
Introducing FSter
Introducing FSterIntroducing FSter
Introducing FSteritsmesrl
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQLNorvald Ryeng
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basicwali1195189
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data StorageMingHo Chang
 

Was ist angesagt? (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
 

Ähnlich wie 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 AnswersVineet 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 Objectshiren.joshi
 
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 LondonPhase2
 
php databse handling
php databse handlingphp databse handling
php databse handlingkunj desai
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
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 5John Coggeshall
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questionssekar c
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHPNisa Soomro
 
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 ModuleKatie Gulley
 
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 doDave Stokes
 

Ähnlich wie 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
 

Kürzlich hochgeladen

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
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...ranjana rawat
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
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...Call Girls in Nagpur High Profile
 
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
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
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 Performancesivaprakash250
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
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...roncy bisnoi
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
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...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Kürzlich hochgeladen (20)

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
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...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
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...
 
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, ...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
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
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
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...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
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...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.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"; }