IDIOT DEVELOPER

Connecting to Database in PDO (PHP Data Object)
Connecting to Database in PDO (PHP Data Object)

In previous post Introduction to PDO  , we have learn about a general introduction on PDO (PHP Data Object). In this post, we are going to learn about how to connect to a MySQL Database. There exist a number of database, each have a slightly different connection method. Below, the method to connect to some of the most popular databases are shown.

 

Video

 

General Format of PDO

 


$DB = new PDO("mysql:host=$host;dbname=$dbname, $user, $pass");

 

Here:
1. $DB is the new PDO Object which is going to handle the Database.
2. mysql is the type of database.
3. $host is the host name for the database.
4. $dbname is the database name to which you wants to connect.
5. $user is the username for the database.
6. $pass is the password for the database.

 

NOTE: Always use try/catch block to connect to database as their are chances of getting an exception, and by chance if their is any exception then you can handle it easily.

 

Connecting to MySQL Database

 


$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

 

Connecting to MS SQL Database

 


$DB = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");

 

Connecting to Sybase Database

 


$DB = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");

 

Connecting to SQLite Database

 


$DB = new PDO("sqlite:my/database/path/database.db");

 

MySQL, MS SQL, and Sybase appear to have same format but SQLite have slightly different format. SQLite on require the database file path.

 

To close a database connection, simply make the $DB null.

 


$DB = null;

 

 


<?php

define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DBNAME', 'tut');

try{
  $db = new PDO( 'mysql:host=' . HOST . '; dbname=' . DBNAME, USERNAME, PASSWORD );
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  return $db;
}catch(PDOExecption $e){
  echo 'Connection Failed: ' . $e->getMessage();
}

?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *