Skip to content

Class Database PDO

edited June 13 in PHP

Having a private PDO variable helps ease of mind when it comes to security.

Setup your database class as follows:

<?php
	class Database{
		private $pdo;
      
		function __construct(){
			try{
				$this->pdo = new PDO('mysql:host=LOCALHOST;dbname=DBNAME', 'USER', 'PASS');
				$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			}catch(PDOException $e){
				echo 'Connection failed: '.$e->getMessage();
			} 
		}
		
		function getDatabaseObject(){
			return $this->pdo;
		}
	}
?>

You can then call this database object outside of a class.

$dbo = new Database();
$pdo = $dbo->getDatabaseObject();

If you wish to call this database object inside of a class, using a construct will prepare the PDO variable for you so you can use $this->pdo throughout the class.

<?php
	class Sample{
		private $pdo;
	
		function __construct(){
			$dbo = new Database();
			$this->pdo = $dbo->getDatabaseObject();
		}
		
		//add your gets and sets below
	}
}
Sign In or Register to comment.