We can connect to MySQL the easy way or the other way by writing a MySQL wrapper, that’s upto the programmer. In this post, i will not go for any wrapper or class but will share my approach with PDO, which itself is OO.

I declared a variable $live, this is to switch for local and live server easily, if you don’t want it just remove that piece of code.

<?php
$live = 0 ; // 1=live, 0=local

if($live === 0) :
  $hostname = 'localhost';
  $username = 'admin';
  $password = 'passlocal';
  $database = 'local_db';

elseif($live === 1) :

  $hostname = 'localhost';
  $username = 'admin';
  $password = 'passlive';
  $database = 'live_db';

endif;

if (defined('PDO::ATTR_DRIVER_NAME')):
  if(extension_loaded ('PDO')):
    if(extension_loaded ('pdo_mysql')):
    try {

      $dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      //echo 'Connected to database&lt;br />';

    }
    catch(PDOException $e)
    {
      echo $e->getMessage();
    }
    else:
      echo "PDO support is available and is loaded, but it seems that pdo mysql extension is not loaded.";
    endif;
  else:
    echo "PDO support is available, but it seems that it is not loaded.";
  endif;
else:
  echo "Sorry, but it seems that PDO support is not available.";
endif;
?>

In the 1st few lines of if statement we check that whether POD driver is available if yes, is it loaded?. By default PHP already load this module and it is installed by default. but this is in case some thing is wrong. You can uncomment the echo line to make sure you are connected with the database.