Return to Snippet

Revision: 53306
at November 18, 2011 14:25 by cdog


Initial Code
<?php
/*****************

SIMPLE DATABASE CLASS
http://www.onitindustries.com

----------------------

HOW TO USE

----------------------
// Calling the class and connecting

$DB = new db();                                                              // start database class
$DB->connect($c_db_username, $c_db_password, $c_db_database, $c_db_host);    // connect to the database

// Example Query - ARRAY
$results = db::query("SELECT * FROM table", DB_GET_ARRAY);
foreach($results as $result) {
	
	echo $result->column;
	
}

******************/

// DEFINITIONS
define("DB_GET_ROW", "getRow");
define("DB_GET_ARRAY", "fetchArray");

class db {
	
	private $username;
	private $password;
	private $database;
	private $host;
	private $status;
	private $con;
	
	 public static $_query;
	 public static $errors = array();
	
	function __construct() {
		
	}
	
	// connect to the database
	function connect($username, $password, $database, $host = 'localhost')
	{
		
		$this->username = $username;
		$this->password = $password;
		$this->database = $database;
		$this->host     = $host;
		
		$con    = mysql_connect(''.$this->host.'', ''.$this->username.'', ''.$this->password.'');

		$select = mysql_select_db($this->database, $con);
		
		if(!$con) {
			
			$this->errors[] = 'Could not connect to the database';
			
		} elseif(!$select) {
			
			$this->errors[] = 'Could not select the database';
			
		}  else {
			
			$this->con = $con;
		}
		
		return ;
		
	}
	
	// Close connection
	public function disconnect()
	{
		mysql_close($this->con);
	}
	
	public function showStatus() {
		
		if(!$this->status) {
			
			foreach($this->errors as $value) {
				
				echo $value.'<br>';
				
			}
			
		} else {
			
			echo 'all good';
		}
		
	}
	
	// process queries
	public static function query($sql, $queryType='')
	{
		db::$_query = @mysql_query($sql);
		
		switch($queryType)
		{
			
			case 'getRow':
			return self::getRow(db::$_query);
			break;
			
			case 'fetchArray':
			return self::fetchArray(db::$_query);
			break;
			
			case 'getCount':
			return self::fetchArray(db::$_query);
			break;
			
			default: '';
		}
		
		return (self::$_query) ? true : false;
	}
	
	// get single row
	function getRow($query='')
	{
		if($query) { self::$_query = $query; }
		
		return @mysql_fetch_row(self::$_query);
	}
	
	// get array
	function fetchArray($query='')
	{
		if($query) { self::$_query = $query; }
		
		while($row = @mysql_fetch_array(self::$_query))
		{
			$result[] = $row;
		}
		
		return $result;
	}
	
	// get last insert id
	public static function last_insert_id()
	{
		return mysql_insert_id();
	}
	
}

?>

Initial URL
http://www.onitindustries.com

Initial Description
Just my simple db class i use

Initial Title
My database class

Initial Tags
class, php

Initial Language
PHP