Return to Snippet

Revision: 30366
at August 13, 2010 00:02 by Knarf


Initial Code
<?php

// ------------------------------------------------------------------
// -                Database class'es				                -
// ------------------------------------------------------------------

	/**
	 *		Main database class
	 *			Works as a layer over PDO. Every static call is forwarded to the PDO object, except for those which are defined
	 *
	 **/

	class DB
	{
		protected static $DB;
		
		private function __construct()	{}
		private function __clone()		{}

		public static function connect($dbname='default', $host='localhost', $user='root', $password='')
		{
			try {
				// connects to the database
				self::$DB = new PDO("mysql:dbname=$dbname;host:=$host" , $user , $password);
				
				// set the error reporting attribute
				self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			}
			catch(PDOException $e) {
				echo $e->getMessage();
			}
		}
		
		public static function close_connection()
		{
			self::$DB = NULL;
		}
		
		public static function __callStatic($name, $arguments)
		{
			return forward_static_call_array(array(self::$DB, $name), $arguments);
		}
	}


	/**
	 *		A test class
	 *			Using SQLite with 'sqlite::memory:' so that its no need for username, password, etc
	 *			Perfect for quick testing purpose
	 *
	 **/

	class DBtest extends DB
	{
		public static function connect()
		{
			try {
				self::$DB = new PDO("sqlite::memory:");									// connect to database
				echo 'database created in memory <br /> <br />';						// only at debug mode - @TODO: remove it
				self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);		// set the error reporting attribute
			}
			catch(PDOException $e) {
				echo $e->getMessage();
			}
		}
	}

// ------------------------------------------------------------------
// -                Initilize a standard connection                 -
// ------------------------------------------------------------------


include 'config.php';

$dbh::connect(	$config['db']['default']['dbname'],
				$config['db']['default']['host'],
				$config['db']['default']['username'],
				$config['db']['default']['password']
			);

			
?>

Initial URL


Initial Description
A simple wrapper class for MySql around PDO. Also an example on how to use this wrapper for SQLite.

Initial Title
Simple MySQL wrapper around PDO

Initial Tags
mysql, php

Initial Language
PHP