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

PPT
PHP - PDO Objects
PPT
Quebec pdo
PDF
PHP and Mysql
ODP
Adodb Pdo Presentation
PPT
Database presentation
PPT
Php MySql For Beginners
ODP
Database Connection With Mysql
PHP - PDO Objects
Quebec pdo
PHP and Mysql
Adodb Pdo Presentation
Database presentation
Php MySql For Beginners
Database Connection With Mysql

What's hot (18)

PPT
MYSQL - PHP Database Connectivity
PDF
PDO Basics - PHPMelb 2014
PDF
Sqlite perl
PDF
Quebec pdo
PDF
Introduction to php database connectivity
PPT
PHP and MySQL
PDF
Idoc script beginner guide
PDF
&lt;img src="../i/r_14.png" />
PDF
Advanced Querying with CakePHP 3
PPTX
Mysql
PPTX
Database Connectivity in PHP
PDF
4.3 MySQL + PHP
PPT
ODP
DrupalCon Chicago Practical MongoDB and Drupal
PDF
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
PPT
30 5 Database Jdbc
PDF
Php summary
PPTX
Php and database functionality
MYSQL - PHP Database Connectivity
PDO Basics - PHPMelb 2014
Sqlite perl
Quebec pdo
Introduction to php database connectivity
PHP and MySQL
Idoc script beginner guide
&lt;img src="../i/r_14.png" />
Advanced Querying with CakePHP 3
Mysql
Database Connectivity in PHP
4.3 MySQL + PHP
DrupalCon Chicago Practical MongoDB and Drupal
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
30 5 Database Jdbc
Php summary
Php and database functionality
Ad

Viewers also liked (12)

PDF
Michael_Watson_Mobile
PPT
Saha Hadid
PPT
Pp 410
PDF
PPS
Cuques de llum facebook
PPTX
How to validate your product idea, creating value for customers
PPTX
The Secondary Industry
PDF
Research on Comparative Study of Different Mobile Operating System_Part-2
PPT
Search & User Optymalization (SUO) na przykładzie serwisu Motofakty.pl;
PPT
What was life like on board ship 500 years ago
PDF
Ca delegation letter to Secretary Chao re caltrain 2.3.17
PDF
HTTPS bez wymówek
Michael_Watson_Mobile
Saha Hadid
Pp 410
Cuques de llum facebook
How to validate your product idea, creating value for customers
The Secondary Industry
Research on Comparative Study of Different Mobile Operating System_Part-2
Search & User Optymalization (SUO) na przykładzie serwisu Motofakty.pl;
What was life like on board ship 500 years ago
Ca delegation letter to Secretary Chao re caltrain 2.3.17
HTTPS bez wymówek
Ad

Similar to Php Data Objects (20)

PDF
PHP Data Objects
PPT
Introducing PHP Data Objects
PPTX
working with PHP & DB's
PPT
php databse handling
PPTX
Php talk
PDF
Web 10 | PHP with MySQL
PDF
The History of PHPersistence
PDF
wee
PDF
Advanced Php - Macq Electronique 2010
PPT
download presentation
PPTX
Database Programming
PDF
Top 100-php-interview-questions-and-answers-are-below-120816023558-phpapp01
PPTX
Database Basics
PPTX
Pdo – php database extension-Phpgurukul
PDF
ElePHPant7 - Introduction to PHP7
DOCX
100 PHP question and answer
PDF
Stored Procedure
PPT
Migrating from PHP 4 to PHP 5
PDF
Top 100 PHP Interview Questions and Answers
PHP Data Objects
Introducing PHP Data Objects
working with PHP & DB's
php databse handling
Php talk
Web 10 | PHP with MySQL
The History of PHPersistence
wee
Advanced Php - Macq Electronique 2010
download presentation
Database Programming
Top 100-php-interview-questions-and-answers-are-below-120816023558-phpapp01
Database Basics
Pdo – php database extension-Phpgurukul
ElePHPant7 - Introduction to PHP7
100 PHP question and answer
Stored Procedure
Migrating from PHP 4 to PHP 5
Top 100 PHP Interview Questions and Answers

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Spectroscopy.pptx food analysis technology
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx
Building Integrated photovoltaic BIPV_UPV.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
Empathic Computing: Creating Shared Understanding
Digital-Transformation-Roadmap-for-Companies.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Spectroscopy.pptx food analysis technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows

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]); }