object oriented php pdo connection


I have created two class to config and register class to add the email id to database.

Why did I used pdo to connect?

ANS:SImple sanitize the input data to protect the database.

Config.php

<?php

//db connection class using singleton pattern
class dbConn{

//variable to hold connection object.
protected static $db;

//private construct - class cannot be instatiated externally.
private function __construct() {

try {
// assign PDO object to db variable
self::$db = new PDO( 'mysql:host=localhost;dbname=didit','root','' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error: " . $e->getMessage();
}

}

// get connection function. Static method - accessible without instantiation
public static function getConnection() {

//Guarantees single instance, if no connection object exists then create one.
if (!self::$db) {
//new connection object.
new dbConn();
}

//return connection.
return self::$db;
}

}//end class

?>

 

register.php

 

<?php

require_once 'conf.php';

class Didit {
    
    public $conn;
            
    /**
    * Short description for file   
    * @param string  $first_name    description
    * 
    * @return boolean
    */
    
    public function register_email($reg_email)
    {    
        $conn = dbConn::getConnection();
        
        $querychk = $conn->query("select * from User where Email = '$reg_email' ")->rowCount();        
        if($querychk <= 0)
        {            
            $query1 = $conn->prepare("INSERT into User(Email) VALUES (?)");
            $query1exec = $query1->execute(array($reg_email));
            return $query1exec;            
        } else {
            return -1;        
        }        
    }
    
}
    
?>

 

Advertisements
About

myself pramodh kumar yet another php developer from India and have worked on oops,procedural,yii framework,codeigniter,wordpress,joomla,api and more.

Tagged with: , , , , ,
Posted in php

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow php tutorial on WordPress.com
categories
Calendar
December 2014
M T W T F S S
« Nov   Jan »
1234567
891011121314
15161718192021
22232425262728
293031  
Follow me on Twitter
Blog Stats
  • 74,607 hits
%d bloggers like this: