ad

Friday, 17 April 2015

Connect to database using PDO extension and error handling

First off, those who don't know what database is, in lay man's term it's a place where you can store,
update or retrieve information. Like, username, password, user IP address and much more!

Let's start by learning how to connect to database. Note that you will need PHP v5.1.0 as we'll be using PDO(PHP data objects) extension - extension is something that's usually added later on to add more functionality. PDO extension is used to access databases.

Whenever you're ready, lets get to it.

PDO is a class, so we needa create an instance off it. And if you head over to PHP manual, http://php.net/manual/en/class.pdo.php it shows us that there's a constructor that requires certain things. First parameter we provide it database engine name, host and databse name. Then user and pass.

$host    = "";
$db        = "";
$user    = "";
$pass    = "";
$Connection_object = new PDO('mysql:host='. $host . ';dbname=' . $db, $user, $pass);



You've now connected to database, but how do you make sure? Well PHP provides a way to hande error. Here's the syntax, you TRY, then you CATCH, you provide catch keyword the class name which's Exception, and a variable, which then will turn into an object so you can call its methods.

$host    = "localhost";
$db        = "forum";
$user    = "root";
$pass    = "hpdevsami";

try{
    $Connection_object = new PDO('mysql:host='. $host . ';dbname=' . $db, $user, $pass);
    throw new Exception("error");
}catch(Exception $m){
    echo $m->getMessage();
}

   
Now your $Connection_object is an object and has methods like prepare, execute etc.. which can then be used make queries, fetch data etc..

Useful links:
Exception class:
http://php.net/manual/en/class.exception.php#exception.props.message

Type hinting:
http://php.net/manual/en/language.oop5.typehinting.php

PDO class:
http://php.net/manual/en/class.pdo.php

No comments:

Post a Comment