SlideShare a Scribd company logo
PHP Data Objects A tour of new features
Introduction PHP Data Objects, (PDO) is a PHP5 extension that defines a lightweight DBMS connection abstraction library (sometimes called data access abstraction library).  PDO provides a  data-access  abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data.  This means that PDO defines a unified interface for creating and maintaining database connections, issuing queries, quoting parameters, traversing result sets, dealing with prepared statements, and error handling. PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.
Installation Guidelines Windows users running PHP 5.1.0 and up  PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:  extension=php_pdo.dll Next, choose the other database-specific DLL files and  enable them in php.ini below php_pdo.dll. For example:  extension=php_pdo.dll extension=php_pdo_firebird.dll extension=php_pdo_mssql.dll extension=php_pdo_mysql.dll extension=php_pdo_oci.dll extension=php_pdo_oci8.dll extension=php_pdo_odbc.dll extension=php_pdo_pgsql.dll extension=php_pdo_sqlite.dll  These DLLs should exist in the system's extension_dir.
Using PDO
Connecting to the Database Let's consider the well-known  MySQL  connection scenario: mysql_connect($host, $user, $password); mysql_select_db($db); In  SQLite , for example, we would write something like the following: $dbh = sqlite_open($db, 0666); In  PostgreSQ L, for example, we would write something like the following: pg_connect("host=$host dbname=$db user=$user password=$password"); Here, we establish a connection and then select the default database for the connection. (OLD /CURRENT TECHNIQUE)
Connecting to the Database – Cont.. Now, let's see what PDO has to offer. As PDO is fully object-oriented, we will be dealing with connection objects, and further interaction with the database will involve calling various methods of these objects.  With PDO, we will always have to explicitly use the connection object, since there is no other way of calling its methods.  Each of the three above connections could be established in the following manner: For MySQL: $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass); For SQLite: $conn = new PDO("sqlite:$db"); For PostgreSQL : $conn = new PDO("pgsql:host=$host dbname=$db", $user, $pass);
Connecting to the Database – Cont.. As you can see, the only part that is changing here is the first argument passed to the PDO constructor. For SQLite, which does not utilize username and password, the second and third arguments can be skipped. SQLite is not a database server, but it is an embedded SQL database library that operates on local files. More information about SQLite can be found at www.sqlite.org and more information about using SQLite with PHP can be found at www.php.net/sqlite.
Connecting to the Database  –  Connection Strings As you have seen in previous example, PDO uses the so-called connection strings (or Data Source Names, abbreviated to DSN) that allow the PDO constructor to select proper driver and pass subsequent method calls to it.  These connection strings or DSNs are different for every database management system and are the only things that you will have to change. Their advantage over using traditional methods of creating database connection is that you don't have to modify your code if you change the database management system. A connection string can be defined in a configuration file and that file gets processed by your application. Should your database (data source) change, you just edit that configuration file and the rest of your code is kept intact.
Connecting to the Database  –  Connection Strings Create the connection object $conn = new PDO( $connStr , $user, $pass); DB connection string and username/password $connStr = 'mysql:host=localhost;dbname=pdo'; $user = 'root'; $pass = 'root'; The three connection strings looked like the following: mysql:host=localhost;dbname=cars sqlite:/path/to/cars.db pgsql:host=localhost dbname=cars As we can see, the prefix (the substring before the first semicolon) always keeps the name of the PDO driver.  Since we don't have to use different functions to create a connection with PDO, this prefix tells us which internal driver should be used. The rest of the string is parsed by that driver to further initiate the connection.
Issuing SQL Queries Previously, we would have had to call different functions, depending on the database: Let's keep our SQL in a single variable $sql = 'SELECT DISTINCT make FROM cars ORDER BY make'; Now, assuming  MySQL : mysql_connect('localhost', 'boss', 'password'); mysql_select_db('cars'); $q = mysql_query($sql); For  SQLite  we would do: $dbh = sqlite_open('/path/to/cars.ldb', 0666); $q = sqlite_query($sql, $dbh); And for  PostgreSQL : pg_connect("host=localhost dbname=cars user=boss  password=password"); $q = pg_query($sql);
Issuing SQL Queries – Cont… Now that we are using PDO, we can do the following: Assume the $connStr variable holds a valid connection string $sql = 'SELECT DISTINCT make FROM cars ORDER BY make'; $conn = new PDO($connStr, 'boss', 'password'); $q = $conn->query($sql); As you can see, doing things the PDO way is not too different from traditional methods of issuing queries. Also, here it should be underlined, that a call to  $conn->query()  is returning another object of class  PDOStatement , unlike the calls to mysql_query(), sqlite_query(), and pg_query(), which return PHP variables of the  resource type.
Issuing SQL Queries – Cont… The PDO class defines a single method for quoting strings so that they can be used safely in queries.  $m = $conn->quote($make); $q = $conn->query("SELECT sum(price) FROM cars WHERE make=$m"); Now that we have issued our query, we will want to see its results. As the query in the last example will always return just one row, we will want more rows. Again, the three databases will require us to call different functions on the $q variable that was returned from one of the three calls to mysql_query(), sqlite_query(), or pg_query(). So our code for getting all the cars will look similar to this:
Assume the query is in the $sql variable $sql = "SELECT DISTINCT make FROM cars ORDER BY make"; For  MySQL : $q = mysql_query($sql); while($r = mysql_fetch_assoc($q))  {  echo $r['make'], "\n"; } For  SQLite : $q = sqlite_query($dbh, $sql); while($r = sqlite_fetch_array($q, SQLITE_ASSOC))  {  echo $r['make'], "\n"; } And, finally,  PostgreSQL : $q = pg_query($sql); while($r = pg_fetch_assoc($q))  {  echo $r['make'], "\n"; }
Issuing SQL Queries – Cont… As you may already have guessed, things are pretty straightforward when it comes to PDO: We don't care what the underlying database is, and the methods for fetching rows are the same across all databases. So, the above code could be rewritten for PDO in the following way: mysql_fetch_array(), sqlite_fetch_array() without the second parameter, or pg_fetch_array().) $q = $conn->query("SELECT DISTINCT make FROM cars ORDER BY  make"); while($r = $q->fetch( PDO::FETCH_ASSOC ))  {  echo $r['make'], "\n"; } Nothing is different from what happens before. One thing to note here is that we explicitly specified the  PDO::FETCH_ASSOC  fetch style constant here, since PDO's default behavior is to fetch the result rows as arrays indexed both by column name and number. (This behavior is similar to mysql_fetch_array(), sqlite_fetch_array() without the second parameter, or pg_fetch_array().)
Issue the query $q = $conn->query(&quot;SELECT authors.id AS authorId, firstName,  lastName, books.* FROM authors, books WHERE author=authors.id ORDER BY title&quot;); $books = $q->fetchAll(PDO::FETCH_ASSOC) ; foreach($books as $r)  {   ?>  <tr>  <td><a href=&quot;author.php?id=<?=$r['authorId']?>&quot;>  <?=htmlspecialchars(&quot;$r[firstName] $r[lastName]&quot;)?></a></td>  <td><?=htmlspecialchars($r['title'])?></td>  <td><?=htmlspecialchars($r['isbn'])?></td>  <td><?=htmlspecialchars($r['publisher'])?></td>  <td><?=htmlspecialchars($r['year'])?></td>  <td><?=htmlspecialchars($r['summary'])?></td>  </tr>  <?php  }  ?>
Issuing SQL Queries – Cont… For example, MySQL extends the SQL syntax with this form of insert: INSERT INTO mytable SET x=1, y='two'; This kind of SQL code is not portable, as other databases do not understand this way of doing inserts. To ensure that your inserts work across databases, you should replace the above code with : INSERT INTO mytable(x, y) VALUES(1, 'two');
Error Handling Of course, the above examples didn't provide for any error checking, so they are not very useful for real-life applications.  When working with a database, we should check for errors when opening the connection to the database, when selecting the database and after issuing every query.  Most web applications, however, just need to display an error message when something goes wrong (without going into error detail, which could reveal some sensitive information).  However, when debugging an error, you (as the developer) would need the most detailed error information possible so that you can debug the error in the shortest possible time. One simplistic scenario would be to abort the script and present the error message (although this is something you probably would not want to do).
Error Handling – Cont… Depending on the database, our code might look like this: For Sqlite $dbh = sqlite_open('/path/to/cars.ldb', 0666) or die ('Error opening SQLite database: ' . sqlite_error_string(sqlite_last_error($dbh)) ); $q = sqlite_query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;,$dbh) or  die('Could not execute query because: '. sqlite_error_string(sqlite_last_error($dbh)) ); For PostgreSQL pg_connect(&quot;host=localhost dbname=cars;user=boss;password=password&quot;)  or die('Could not connect to PostgreSQL: '.  pg_last_error() ); $q = pg_query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;) or die('Could not execute query because: ' .  pg_last_error() ); As you can see, error handling is starting to get a bit different for SQLite compared to MySQL and PostgreSQL. (Note the call to sqlite_error_string (sqlite_last_error($dbh)).)
Error Handling – Cont… PDO error handling Assume the connection string is one of the following: // $connStr = 'mysql:host=localhost;dbname=cars' // $connStr = 'sqlite:/path/to/cars.ldb'; // $connStr = 'pgsql:host=localhost dbname=cars'; try  {  $conn = new PDO($connStr, 'boss', 'password'); }  catch(PDOException $pe)  {  die('Could not connect to the database because: ' .  $pe->getMessage(); } $q = $conn->query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;);  if(!$q)  {  $ei = $conn->errorInfo();  die('Could not execute query because: ' . $ei[2]); }

More Related Content

What's hot (18)

PPT
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
PDF
PDO Basics - PHPMelb 2014
andrewdotcom
 
PDF
Sqlite perl
Ashoka Vanjare
 
PDF
Quebec pdo
Rengga Aditya
 
PDF
Introduction to php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
PPT
PHP and MySQL
webhostingguy
 
PDF
Idoc script beginner guide
Vinay Kumar
 
PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
PPTX
Mysql
lotlot
 
PPTX
Database Connectivity in PHP
Taha Malampatti
 
PDF
4.3 MySQL + PHP
Jalpesh Vasa
 
PPT
MySQL
Gouthaman V
 
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
PDF
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
fntsofttech
 
PPT
30 5 Database Jdbc
phanleson
 
PDF
Php summary
Michelle Darling
 
PPTX
Php and database functionality
Sayed Ahmed
 
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
PDO Basics - PHPMelb 2014
andrewdotcom
 
Sqlite perl
Ashoka Vanjare
 
Quebec pdo
Rengga Aditya
 
Introduction to php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
PHP and MySQL
webhostingguy
 
Idoc script beginner guide
Vinay Kumar
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
Mysql
lotlot
 
Database Connectivity in PHP
Taha Malampatti
 
4.3 MySQL + PHP
Jalpesh Vasa
 
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
fntsofttech
 
30 5 Database Jdbc
phanleson
 
Php summary
Michelle Darling
 
Php and database functionality
Sayed Ahmed
 

Viewers also liked (12)

PDF
Michael_Watson_Mobile
Michael Watson
 
PPT
Saha Hadid
joha1987
 
PPT
Pp 410
ryno1217
 
PDF
Agip Grease 30 - Fornid
Fornid - Articoli tecnici e industriali
 
PPS
Cuques de llum facebook
Albert Rocarols
 
PPTX
How to validate your product idea, creating value for customers
Smitha Hemmigae
 
PPTX
The Secondary Industry
Jong Azores
 
PDF
Research on Comparative Study of Different Mobile Operating System_Part-2
Zulkar Naim
 
PPT
Search & User Optymalization (SUO) na przykładzie serwisu Motofakty.pl;
3camp
 
PPT
What was life like on board ship 500 years ago
ismhistory
 
PDF
Ca delegation letter to Secretary Chao re caltrain 2.3.17
Adina Levin
 
PDF
HTTPS bez wymówek
3camp
 
Michael_Watson_Mobile
Michael Watson
 
Saha Hadid
joha1987
 
Pp 410
ryno1217
 
Cuques de llum facebook
Albert Rocarols
 
How to validate your product idea, creating value for customers
Smitha Hemmigae
 
The Secondary Industry
Jong Azores
 
Research on Comparative Study of Different Mobile Operating System_Part-2
Zulkar Naim
 
Search & User Optymalization (SUO) na przykładzie serwisu Motofakty.pl;
3camp
 
What was life like on board ship 500 years ago
ismhistory
 
Ca delegation letter to Secretary Chao re caltrain 2.3.17
Adina Levin
 
HTTPS bez wymówek
3camp
 
Ad

Similar to Php Data Objects (20)

PPT
P H P Part I I, By Kian
phelios
 
PPT
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
ODP
Into to DBI with DBD::Oracle
byterock
 
PPTX
working with PHP & DB's
Hi-Tech College
 
ODP
Exploring Symfony's Code
Wildan Maulana
 
PPT
Php frameworks
Anil Kumar Panigrahi
 
PPT
Working with databases in Perl
Laurent Dami
 
PPTX
Learn PHP Lacture2
ADARSH BHATT
 
PPT
DBIx-DataModel v2.0 in detail
Laurent Dami
 
PPTX
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
PPT
PHP Workshop Notes
Pamela Fox
 
PPT
Slick Data Sharding: Slides from DrupalCon London
Phase2
 
PDF
PHP Data Objects
Wez Furlong
 
PPT
Ubi comp27nov04
mohamed ashraf
 
PPT
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
PPT
Framework
Nguyen Linh
 
PPT
Php classes in mumbai
aadi Surve
 
PPT
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
PPT
Security.ppt
webhostingguy
 
P H P Part I I, By Kian
phelios
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
Into to DBI with DBD::Oracle
byterock
 
working with PHP & DB's
Hi-Tech College
 
Exploring Symfony's Code
Wildan Maulana
 
Php frameworks
Anil Kumar Panigrahi
 
Working with databases in Perl
Laurent Dami
 
Learn PHP Lacture2
ADARSH BHATT
 
DBIx-DataModel v2.0 in detail
Laurent Dami
 
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
PHP Workshop Notes
Pamela Fox
 
Slick Data Sharding: Slides from DrupalCon London
Phase2
 
PHP Data Objects
Wez Furlong
 
Ubi comp27nov04
mohamed ashraf
 
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
Framework
Nguyen Linh
 
Php classes in mumbai
aadi Surve
 
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
webhostingguy
 
Ad

Recently uploaded (20)

PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Digital Circuits, important subject in CS
contactparinay1
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

Php Data Objects

  • 1. PHP Data Objects A tour of new features
  • 2. Introduction PHP Data Objects, (PDO) is a PHP5 extension that defines a lightweight DBMS connection abstraction library (sometimes called data access abstraction library). PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. This means that PDO defines a unified interface for creating and maintaining database connections, issuing queries, quoting parameters, traversing result sets, dealing with prepared statements, and error handling. PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.
  • 3. Installation Guidelines Windows users running PHP 5.1.0 and up PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file: extension=php_pdo.dll Next, choose the other database-specific DLL files and enable them in php.ini below php_pdo.dll. For example: extension=php_pdo.dll extension=php_pdo_firebird.dll extension=php_pdo_mssql.dll extension=php_pdo_mysql.dll extension=php_pdo_oci.dll extension=php_pdo_oci8.dll extension=php_pdo_odbc.dll extension=php_pdo_pgsql.dll extension=php_pdo_sqlite.dll These DLLs should exist in the system's extension_dir.
  • 5. Connecting to the Database Let's consider the well-known MySQL connection scenario: mysql_connect($host, $user, $password); mysql_select_db($db); In SQLite , for example, we would write something like the following: $dbh = sqlite_open($db, 0666); In PostgreSQ L, for example, we would write something like the following: pg_connect(&quot;host=$host dbname=$db user=$user password=$password&quot;); Here, we establish a connection and then select the default database for the connection. (OLD /CURRENT TECHNIQUE)
  • 6. Connecting to the Database – Cont.. Now, let's see what PDO has to offer. As PDO is fully object-oriented, we will be dealing with connection objects, and further interaction with the database will involve calling various methods of these objects. With PDO, we will always have to explicitly use the connection object, since there is no other way of calling its methods. Each of the three above connections could be established in the following manner: For MySQL: $conn = new PDO(&quot;mysql:host=$host;dbname=$db&quot;, $user, $pass); For SQLite: $conn = new PDO(&quot;sqlite:$db&quot;); For PostgreSQL : $conn = new PDO(&quot;pgsql:host=$host dbname=$db&quot;, $user, $pass);
  • 7. Connecting to the Database – Cont.. As you can see, the only part that is changing here is the first argument passed to the PDO constructor. For SQLite, which does not utilize username and password, the second and third arguments can be skipped. SQLite is not a database server, but it is an embedded SQL database library that operates on local files. More information about SQLite can be found at www.sqlite.org and more information about using SQLite with PHP can be found at www.php.net/sqlite.
  • 8. Connecting to the Database – Connection Strings As you have seen in previous example, PDO uses the so-called connection strings (or Data Source Names, abbreviated to DSN) that allow the PDO constructor to select proper driver and pass subsequent method calls to it. These connection strings or DSNs are different for every database management system and are the only things that you will have to change. Their advantage over using traditional methods of creating database connection is that you don't have to modify your code if you change the database management system. A connection string can be defined in a configuration file and that file gets processed by your application. Should your database (data source) change, you just edit that configuration file and the rest of your code is kept intact.
  • 9. Connecting to the Database – Connection Strings Create the connection object $conn = new PDO( $connStr , $user, $pass); DB connection string and username/password $connStr = 'mysql:host=localhost;dbname=pdo'; $user = 'root'; $pass = 'root'; The three connection strings looked like the following: mysql:host=localhost;dbname=cars sqlite:/path/to/cars.db pgsql:host=localhost dbname=cars As we can see, the prefix (the substring before the first semicolon) always keeps the name of the PDO driver. Since we don't have to use different functions to create a connection with PDO, this prefix tells us which internal driver should be used. The rest of the string is parsed by that driver to further initiate the connection.
  • 10. Issuing SQL Queries Previously, we would have had to call different functions, depending on the database: Let's keep our SQL in a single variable $sql = 'SELECT DISTINCT make FROM cars ORDER BY make'; Now, assuming MySQL : mysql_connect('localhost', 'boss', 'password'); mysql_select_db('cars'); $q = mysql_query($sql); For SQLite we would do: $dbh = sqlite_open('/path/to/cars.ldb', 0666); $q = sqlite_query($sql, $dbh); And for PostgreSQL : pg_connect(&quot;host=localhost dbname=cars user=boss password=password&quot;); $q = pg_query($sql);
  • 11. Issuing SQL Queries – Cont… Now that we are using PDO, we can do the following: Assume the $connStr variable holds a valid connection string $sql = 'SELECT DISTINCT make FROM cars ORDER BY make'; $conn = new PDO($connStr, 'boss', 'password'); $q = $conn->query($sql); As you can see, doing things the PDO way is not too different from traditional methods of issuing queries. Also, here it should be underlined, that a call to $conn->query() is returning another object of class PDOStatement , unlike the calls to mysql_query(), sqlite_query(), and pg_query(), which return PHP variables of the resource type.
  • 12. Issuing SQL Queries – Cont… The PDO class defines a single method for quoting strings so that they can be used safely in queries. $m = $conn->quote($make); $q = $conn->query(&quot;SELECT sum(price) FROM cars WHERE make=$m&quot;); Now that we have issued our query, we will want to see its results. As the query in the last example will always return just one row, we will want more rows. Again, the three databases will require us to call different functions on the $q variable that was returned from one of the three calls to mysql_query(), sqlite_query(), or pg_query(). So our code for getting all the cars will look similar to this:
  • 13. Assume the query is in the $sql variable $sql = &quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;; For MySQL : $q = mysql_query($sql); while($r = mysql_fetch_assoc($q)) { echo $r['make'], &quot;\n&quot;; } For SQLite : $q = sqlite_query($dbh, $sql); while($r = sqlite_fetch_array($q, SQLITE_ASSOC)) { echo $r['make'], &quot;\n&quot;; } And, finally, PostgreSQL : $q = pg_query($sql); while($r = pg_fetch_assoc($q)) { echo $r['make'], &quot;\n&quot;; }
  • 14. Issuing SQL Queries – Cont… As you may already have guessed, things are pretty straightforward when it comes to PDO: We don't care what the underlying database is, and the methods for fetching rows are the same across all databases. So, the above code could be rewritten for PDO in the following way: mysql_fetch_array(), sqlite_fetch_array() without the second parameter, or pg_fetch_array().) $q = $conn->query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;); while($r = $q->fetch( PDO::FETCH_ASSOC )) { echo $r['make'], &quot;\n&quot;; } Nothing is different from what happens before. One thing to note here is that we explicitly specified the PDO::FETCH_ASSOC fetch style constant here, since PDO's default behavior is to fetch the result rows as arrays indexed both by column name and number. (This behavior is similar to mysql_fetch_array(), sqlite_fetch_array() without the second parameter, or pg_fetch_array().)
  • 15. Issue the query $q = $conn->query(&quot;SELECT authors.id AS authorId, firstName, lastName, books.* FROM authors, books WHERE author=authors.id ORDER BY title&quot;); $books = $q->fetchAll(PDO::FETCH_ASSOC) ; foreach($books as $r) { ?> <tr> <td><a href=&quot;author.php?id=<?=$r['authorId']?>&quot;> <?=htmlspecialchars(&quot;$r[firstName] $r[lastName]&quot;)?></a></td> <td><?=htmlspecialchars($r['title'])?></td> <td><?=htmlspecialchars($r['isbn'])?></td> <td><?=htmlspecialchars($r['publisher'])?></td> <td><?=htmlspecialchars($r['year'])?></td> <td><?=htmlspecialchars($r['summary'])?></td> </tr> <?php } ?>
  • 16. Issuing SQL Queries – Cont… For example, MySQL extends the SQL syntax with this form of insert: INSERT INTO mytable SET x=1, y='two'; This kind of SQL code is not portable, as other databases do not understand this way of doing inserts. To ensure that your inserts work across databases, you should replace the above code with : INSERT INTO mytable(x, y) VALUES(1, 'two');
  • 17. Error Handling Of course, the above examples didn't provide for any error checking, so they are not very useful for real-life applications. When working with a database, we should check for errors when opening the connection to the database, when selecting the database and after issuing every query. Most web applications, however, just need to display an error message when something goes wrong (without going into error detail, which could reveal some sensitive information). However, when debugging an error, you (as the developer) would need the most detailed error information possible so that you can debug the error in the shortest possible time. One simplistic scenario would be to abort the script and present the error message (although this is something you probably would not want to do).
  • 18. Error Handling – Cont… Depending on the database, our code might look like this: For Sqlite $dbh = sqlite_open('/path/to/cars.ldb', 0666) or die ('Error opening SQLite database: ' . sqlite_error_string(sqlite_last_error($dbh)) ); $q = sqlite_query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;,$dbh) or die('Could not execute query because: '. sqlite_error_string(sqlite_last_error($dbh)) ); For PostgreSQL pg_connect(&quot;host=localhost dbname=cars;user=boss;password=password&quot;) or die('Could not connect to PostgreSQL: '. pg_last_error() ); $q = pg_query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;) or die('Could not execute query because: ' . pg_last_error() ); As you can see, error handling is starting to get a bit different for SQLite compared to MySQL and PostgreSQL. (Note the call to sqlite_error_string (sqlite_last_error($dbh)).)
  • 19. Error Handling – Cont… PDO error handling Assume the connection string is one of the following: // $connStr = 'mysql:host=localhost;dbname=cars' // $connStr = 'sqlite:/path/to/cars.ldb'; // $connStr = 'pgsql:host=localhost dbname=cars'; try { $conn = new PDO($connStr, 'boss', 'password'); } catch(PDOException $pe) { die('Could not connect to the database because: ' . $pe->getMessage(); } $q = $conn->query(&quot;SELECT DISTINCT make FROM cars ORDER BY make&quot;); if(!$q) { $ei = $conn->errorInfo(); die('Could not execute query because: ' . $ei[2]); }