phpeveryday.com

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


PDO: Portable Connection to Database

Tag: PHP Data Objects, PDO, extension, PHP extension, database connection   Category: PHP Database
post: 19 Apr 2008 read: 857


PHP Data Objects (PDO) Step By Step Tutorial - Part 4: Working with PDO, we define what database that we want to use. We write a line code for connect to database. When we want to change database, we just rewrite one line code. Not all code. Below is PDO code to connect to several database:

// 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);

Look following code:


<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";
$dbpath		= "c:/test.db";

// switching
switch($dbtype){
  case "mysql":
    $dbconn = "mysql:host=$dbhost;dbname=$dbname";
    break;
  
  case "sqlite":
    $dbconn = "sqlite:$dbpath";
	break;
  
  case "postgresql":
    $dbconn = "pgsql:host=$host dbname=$db";
	break;
}

// database connection
$conn = new PDO($dbconn,$user,$pass);

?>

This is sample mode to write connection. It is more portable, because when we change database, we just change at configuration part (may be only change line 3).




| 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