Example PDO Singleton Class

Posted by & filed under mySQL, PHP.

<?php
/**
 * Example PDO class with basic function example.
 * Instead of using different credentials for local and remote db,
 * you could add the same users creds to both local and remote.
 */
class Database {
    
    // local connection
    public $local = array(
	'host' => 'localhost',
	'user' => 'root',
	'pass' => '',
	'db' => 'dbname'
    );
    
    // remote connection
    public $remote = array(
	'host' => 'localhost',
	'user' => 'user',
	'pass' => 'pw',
	'db' => 'dbname'
    );
    
    private static $_singleton;
    private $dbh;

    private function __construct() {
	$creds = ($_SERVER['SERVER_ADDR'] == '127.0.0.1') ? $this->local : $this->remote;
	$this->_connect(
	    $creds['host'],
	    $creds['user'],
	    $creds['pass'],
	    $creds['db']
	);
	// set error level to warnings
	$this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    }

    public static function getInstance() {
        if(!self::$_singleton) {
            self::$_singleton = new Database();
        }
        return self::$_singleton;
    }

    private function _connect($host, $user, $pass, $db) {
	try {
	    $this->dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
	    return true;
	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }

    public function getUser($un, $pw){
	try {
	    $sql = "SELECT username FROM user WHERE username = :username AND password = :password";

	    $stmt = $this->dbh->prepare($sql);
	    $stmt->bindParam(':username', $un);
	    $stmt->bindParam(':password', $pw);
	    $stmt->execute();

	    $usrObj = $stmt->fetch(PDO::FETCH_OBJ);

	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }

    public function addNews($date){
	try {
	    $sql = "INSERT INTO news (`date`,`content`,`created`) VALUES (:date,:content,:created)";
	    $stmt = $this->dbh->prepare($sql);
	    $stmt->bindParam(':date', $date);
	    $created =  date('Y-m-d H:i:s');
	    $stmt->bindParam(':created',$created);

	    if ($stmt->execute()) {
		return '1';
	    } else {
		return var_export($stmt->errorInfo());
	    }
	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }
    
    public function disconnect() {
        $this->dbh = null;
    }
}
?>

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Bitnami