phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PDO: Error Handling

Tag:    Category: PHP Database
post: 19 Apr 2008 read: 593


PHP Data Objects (PDO) Step By Step Tutorial - Part 6: When everything is okey, we didn't need error checking. But, we never know (especially at real world) what will happen, error handling is needed. We should check for errors when opening the connection to database, select database, and run query.

We can implement error handling at PDO like this:


<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

try{
  // database connection
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
}
catch(PDOException $pe)
{
  die('Connection error, because: ' .$pe->getMessage());
}


// query
$sql = "SELECT title FROM books ORDER BY title";
$q	 = $conn->query($sql);

if(!$q)
{
  die("Execute query error, because: ". $conn->errorInfo());
}

$q->setFetchMode(PDO::FETCH_BOTH);

// fetch
while($r = $q->fetch()){
  print_r($r);
}


?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Joomla: Fast Road to Understand Component Programming
Chart: How to Build Cool Animation Real Time Chart
Email: Send Attachement Mail
SMS : Sending SMS with PHP and ActiveXperts (Part 1)

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


624
posting