Wednesday, 20 May 2015

Connect mysql database with PDO statement

We all know that mysql_ extensions now are deprecated in php 5.5.x and generates E^ deprecated warning.
Because,It was originally introduced in PHP v2.0 for MySQL v3.23, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.

To overcome mysql_extension,  PDO can be used. here we are going to show how to connect mysql database with PDO statement.

Recap--
in mysql_ extension, we used mysql_connect to establish connection to our database.

$conn=mysql_connect("localhost","USER_NAME","PASSWORD");
if(!$conn)
{
  // echo "Connection failed..";
  header("location:error.php");
  exit;
}
if(!mysql_select_db('DATABASE_NAME'))
{
  //echo "Database selection failed..";
  header("location:error.php");
  exit;
}

In PDO We may do something like this..
try
{
 $obj_pdo=new PDO('mysql:host=localhost;dbname=DATABSAE_NAME','USER_NAME','PASSWORD');

$obj_pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $obj_pdo;
}
catch(PDOException $e)
{
      header("location:error.php");
      exit;
}

Explanation---
Here we are using try and catch block to control the success or failure during establishing the connection.
on success, try block will return $obj_pdo object will be used for executing other statements. 
so whenever any error occurs like username or database name or password is incorrect, the catch block will be executed. Here we are redirecting users to error.php page if it fails to establish a connection.
 
This example shows how to create connection to database only. this is the best and simple way to create a connection with database.

See also..
Why mysql_ extension is deprecated ?
How to execute INSERT query/statement with PDO statement.
How to execute SELECT query/statement with PDO statement
How to execute UPDATE query/statement with PDO statement
How to execute DELETE query/statement with PDO statement

No comments:

Post a Comment