SlideShare a Scribd company logo
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
PHP Data Objects(PDO)
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.
Predefined Variables:
PDO::FETCH_ASSOC Specifies that the fetch method shall return each row as an array indexed by column
name.
PDO::FETCH_NUM Specifies that the fetch method shall return each row as an array indexed by column
number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH Specifies that the fetch method shall return each row as an array indexed by both
column name and number as returned in the corresponding result set, starting at
column 0.
PDO::ERRMODE_SILENT Do not raise an error or exception if an error occurs.
PDO::ERRMODE_WARNING Issue a PHP E_WARNING message if an error occurs.
PDO::ERRMODE_EXCEPTION Throw a PDOException if an error occurs.
PDO::ATTR_ERRMODE To set the error mode
PDO::ATTR_PERSISTENT Request a persistent connection, rather than creating a new connection.
Connections and Connection Management:
Connections are established by creating instances of the PDO base class. If there
are any connection errors, a PDOException object will be thrown.
To close the connection, you need to destroy the object by ensuring that all
remaining references to it are deleted—you do this by assigning NULL to the
variable that holds the object. If you don't do this explicitly, PHP will
automatically close the connection when your script ends.
<?php
$dbh = new PDO('mysql:host=localhost:3306;dbname=test', $user, $pass);
// use the connection here
$sth = $dbh->query('SELECT * FROM foo');
// and now we're done; close it
$sth = null;
$dbh = null;
?>
Errors and Error Handling:
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';
/*
Using try/catch around the constructor is still valid even though we set the ER
RMODE to WARNING since
PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
$dbh = new PDO($dsn, $user, $password);
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
// This will cause PDO to throw an error of level E_WARNING instead of an exception
(when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>
PDO::prepare
By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that
prepared statements use fewer resources and thus run faster.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
another sample code:
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
PDO::exec — Execute an SQL statement and return the number of affected rows
This exec function is only applicable to those queries that don’t return results
For example: Database Insert, Update, Delete operations.
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
PDO::query -- executes an SQL statement, returning a result set as a PDOStatement object or FALSE
<?php
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "t";
print $row['color'] . "t";
print $row['calories'] . "n";
}
?>
PDOStatement Object
PDOStatement::columnCount
— Returns the number of
columns in the result set
PDOStatement::rowCount
— Returns the number of rows
affected by the last SQL
statement
<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:n");
$count = $del->rowCount();
print("Deleted $count rows.n");
?>
PDOStatement::setFetchMode
— Set the default fetch mode
for this statement
$stmt = $dbh->query($sql);
$result = $stmt->setFetchMode(PDO::FETCH_NUM);
PDOStatement::execute
— Executes a prepared
statement
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
PDOStatement::fetchAll
— Returns an array containing
all of the result set rows
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:n
");
$result = $sth->fetchAll();
print_r($result);
?>

More Related Content

PDF
Web 8 | Introduction to PHP
PDF
Web 9 | OOP in PHP
PDF
Web 11 | AJAX + JSON + PHP
PDF
Web 4 | Core JavaScript
PPT
Php variables
PPTX
Class 8 - Database Programming
PPT
Class 2 - Introduction to PHP
ODP
Php variables (english)
Web 8 | Introduction to PHP
Web 9 | OOP in PHP
Web 11 | AJAX + JSON + PHP
Web 4 | Core JavaScript
Php variables
Class 8 - Database Programming
Class 2 - Introduction to PHP
Php variables (english)

What's hot (20)

PPTX
PHP PPT FILE
PPT
Php mysql
PDF
Data Types In PHP
PPT
PHP - PDO Objects
PDF
Functions in PHP
PDF
News of the Symfony2 World
PPT
PHP variables
PDF
Learning Perl 6 (NPW 2007)
PDF
Dependency Injection with PHP 5.3
PDF
OSDC.TW - Gutscript for PHP haters
PPT
Class 6 - PHP Web Programming
PPTX
Php & my sql
KEY
Intermediate PHP
PDF
Symfony2 - WebExpo 2010
PPT
PHP and MySQL
PDF
Learning Perl 6
PDF
Idoc script beginner guide
PPT
Php MySql For Beginners
PPTX
Php functions
PPT
PHP Workshop Notes
PHP PPT FILE
Php mysql
Data Types In PHP
PHP - PDO Objects
Functions in PHP
News of the Symfony2 World
PHP variables
Learning Perl 6 (NPW 2007)
Dependency Injection with PHP 5.3
OSDC.TW - Gutscript for PHP haters
Class 6 - PHP Web Programming
Php & my sql
Intermediate PHP
Symfony2 - WebExpo 2010
PHP and MySQL
Learning Perl 6
Idoc script beginner guide
Php MySql For Beginners
Php functions
PHP Workshop Notes
Ad

Similar to Web 10 | PHP with MySQL (20)

PDF
Quebec pdo
PDF
PHP Data Objects
PPTX
Php talk
PPT
Quebec pdo
PPT
Introducing PHP Data Objects
PDF
Sqlite perl
ODP
PHP Data Objects
PPT
Web Technology_10.ppt
PPT
PHP and COM
PPTX
PHP DATABASE MANAGEMENT.pptx
PDF
PHP 5.3 Overview
PPT
Part 2
PPTX
Local SQLite Database with Node for beginners
PDF
Introduction to PHP
PPTX
chapter_Seven Database manipulation using php.pptx
PDF
PHP Programming: Intro
PPT
Php Data Objects
PPTX
PDF
Yves & Zed @ Developer Conference 2013
PDF
Building Testable PHP Applications
Quebec pdo
PHP Data Objects
Php talk
Quebec pdo
Introducing PHP Data Objects
Sqlite perl
PHP Data Objects
Web Technology_10.ppt
PHP and COM
PHP DATABASE MANAGEMENT.pptx
PHP 5.3 Overview
Part 2
Local SQLite Database with Node for beginners
Introduction to PHP
chapter_Seven Database manipulation using php.pptx
PHP Programming: Intro
Php Data Objects
Yves & Zed @ Developer Conference 2013
Building Testable PHP Applications
Ad

More from Mohammad Imam Hossain (20)

PDF
DS & Algo 6 - Offline Assignment 6
PDF
DS & Algo 6 - Dynamic Programming
PDF
DS & Algo 5 - Disjoint Set and MST
PDF
DS & Algo 4 - Graph and Shortest Path Search
PDF
DS & Algo 3 - Offline Assignment 3
PDF
DS & Algo 3 - Divide and Conquer
PDF
DS & Algo 2 - Offline Assignment 2
PDF
DS & Algo 2 - Recursion
PDF
DS & Algo 1 - Offline Assignment 1
PDF
DS & Algo 1 - C++ and STL Introduction
PDF
DBMS 1 | Introduction to DBMS
PDF
DBMS 10 | Database Transactions
PDF
DBMS 3 | ER Diagram to Relational Schema
PDF
DBMS 2 | Entity Relationship Model
PDF
DBMS 7 | Relational Query Language
PDF
DBMS 4 | MySQL - DDL & DML Commands
PDF
DBMS 5 | MySQL Practice List - HR Schema
PDF
TOC 10 | Turing Machine
PDF
TOC 9 | Pushdown Automata
PDF
TOC 8 | Derivation, Parse Tree & Ambiguity Check
DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Dynamic Programming
DS & Algo 5 - Disjoint Set and MST
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Divide and Conquer
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Recursion
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - C++ and STL Introduction
DBMS 1 | Introduction to DBMS
DBMS 10 | Database Transactions
DBMS 3 | ER Diagram to Relational Schema
DBMS 2 | Entity Relationship Model
DBMS 7 | Relational Query Language
DBMS 4 | MySQL - DDL & DML Commands
DBMS 5 | MySQL Practice List - HR Schema
TOC 10 | Turing Machine
TOC 9 | Pushdown Automata
TOC 8 | Derivation, Parse Tree & Ambiguity Check

Recently uploaded (20)

PDF
Module 3: Health Systems Tutorial Slides S2 2025
PDF
Business Ethics Teaching Materials for college
PDF
From loneliness to social connection charting
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PPTX
Pharma ospi slides which help in ospi learning
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Module 3: Health Systems Tutorial Slides S2 2025
Business Ethics Teaching Materials for college
From loneliness to social connection charting
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Open folder Downloads.pdf yes yes ges yes
Cardiovascular Pharmacology for pharmacy students.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
How to Manage Starshipit in Odoo 18 - Odoo Slides
Pharma ospi slides which help in ospi learning
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Onica Farming 24rsclub profitable farm business
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Open Quiz Monsoon Mind Game Prelims.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Anesthesia in Laparoscopic Surgery in India
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx

Web 10 | PHP with MySQL

  • 1. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] PHP Data Objects(PDO) The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Predefined Variables: PDO::FETCH_ASSOC Specifies that the fetch method shall return each row as an array indexed by column name. PDO::FETCH_NUM Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0. PDO::FETCH_BOTH Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0. PDO::ERRMODE_SILENT Do not raise an error or exception if an error occurs. PDO::ERRMODE_WARNING Issue a PHP E_WARNING message if an error occurs. PDO::ERRMODE_EXCEPTION Throw a PDOException if an error occurs. PDO::ATTR_ERRMODE To set the error mode PDO::ATTR_PERSISTENT Request a persistent connection, rather than creating a new connection. Connections and Connection Management: Connections are established by creating instances of the PDO base class. If there are any connection errors, a PDOException object will be thrown. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends. <?php $dbh = new PDO('mysql:host=localhost:3306;dbname=test', $user, $pass); // use the connection here $sth = $dbh->query('SELECT * FROM foo'); // and now we're done; close it $sth = null; $dbh = null; ?> Errors and Error Handling: <?php $dsn = 'mysql:dbname=test;host=127.0.0.1'; $user = 'googleguy'; $password = 'googleguy'; /* Using try/catch around the constructor is still valid even though we set the ER RMODE to WARNING since PDO::__construct will always throw a PDOException if the connection fails. */ try { $dbh = new PDO($dsn, $user, $password);
  • 2. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); exit; } // This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist) $dbh->query("SELECT wrongcolumn FROM wrongtable"); ?> PDO::prepare By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster. <?php $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $value); // insert one row $name = 'one'; $value = 1; $stmt->execute(); // insert another row with different values $name = 'two'; $value = 2; $stmt->execute(); ?> another sample code: <?php /* Execute a prepared statement by passing an array of values */ $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth->execute(array(150, 'red')); $red = $sth->fetchAll(); $sth->execute(array(175, 'yellow')); $yellow = $sth->fetchAll(); ?> PDO::exec — Execute an SQL statement and return the number of affected rows This exec function is only applicable to those queries that don’t return results For example: Database Insert, Update, Delete operations.
  • 3. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> PDO::query -- executes an SQL statement, returning a result set as a PDOStatement object or FALSE <?php $sql = 'SELECT name, color, calories FROM fruit ORDER BY name'; foreach ($conn->query($sql) as $row) { print $row['name'] . "t"; print $row['color'] . "t"; print $row['calories'] . "n"; } ?> PDOStatement Object PDOStatement::columnCount — Returns the number of columns in the result set PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement <?php /* Delete all rows from the FRUIT table */ $del = $dbh->prepare('DELETE FROM fruit'); $del->execute(); /* Return number of rows that were deleted */ print("Return number of rows that were deleted:n"); $count = $del->rowCount(); print("Deleted $count rows.n"); ?> PDOStatement::setFetchMode — Set the default fetch mode for this statement $stmt = $dbh->query($sql); $result = $stmt->setFetchMode(PDO::FETCH_NUM); PDOStatement::execute — Executes a prepared statement <?php /* Execute a prepared statement by binding PHP variables */ $calories = 150; $colour = 'red'; $sth = $dbh->prepare('SELECT name, colour, calories
  • 4. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] FROM fruit WHERE calories < ? AND colour = ?'); $sth->bindParam(1, $calories, PDO::PARAM_INT); $sth->bindParam(2, $colour, PDO::PARAM_STR, 12); $sth->execute(); ?> PDOStatement::fetchAll — Returns an array containing all of the result set rows <?php $sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); /* Fetch all of the remaining rows in the result set */ print("Fetch all of the remaining rows in the result set:n "); $result = $sth->fetchAll(); print_r($result); ?>