Sometimes there is a reason to keep someinformation in different tables in db, so single connect options are not enough to create components to access different tables, so i modified code of DB class to allow multiple DBs connection. One config file is required, so you can create it in fruml/data or in fruml/config folders. Code for config file 'database.php':
<?php $databases = array(); $databases['default']['server'] = DB_SERVER; $databases['default']['port'] = DB_PORT; $databases['default']['username'] = DB_USERNAME; $databases['default']['password'] = DB_PASSWORD; $databases['default']['table'] = DB_DATABASE; $databases['default']['prefix'] = DB_TABLE_PREFIX; $databases['test']['server'] = 'localhost'; $databases['test']['port'] = '3306'; $databases['test']['username'] = 'root'; $databases['test']['password'] = ''; $databases['test']['table'] = 'fruml'; $databases['test']['prefix'] = 'fruml_';
And modified DB class:
<?php
/**
* Database class, handles PDO connections and prepared statement generation.
* @author alex, gijs
* @package DB
*/
class db {
/**
*
* @var unknown_type
*/
private static $_singleton;
private $_connected = array();
private $db;
private static $active_connection = 'default';
private static $databases;
public static $tp;
public static $querylog = array();
private function __construct()
{
$db_config = APP_PATH.'config/database.php';
if(file_exists($db_config))
{
require($db_config);
if(isset($databases))
{
self::$databases = $databases;
}
}
}
public static function tp()
{
return '`'.DB_DATABASE.'`.'.DB_TABLE_PREFIX;
}
public static function getInstance($db = 'default')
{
if(isset(self::$databases[$db]))
{
self::$active_connection = $db;
self::$tp = '`'.self::$databases[self::$active_connection]['table'].'`.'.self::$databases[self::$active_connection]['prefix'];
}
if(is_null(self::$_singleton)) {
self::$_singleton = new DB();
}
return self::$_singleton;
}
public function connect() {
try {
$this->db = new PDO('mysql:host='.self::$databases[self::$active_connection]['server'].';port='.self::$databases[self::$active_connection]['port'].';dbname='.self::$databases[self::$active_connection]['table'], self::$databases[self::$active_connection]['username'], self::$databases[self::$active_connection]['password']);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->exec("set names utf8");
$this->_connected[self::$active_connection] = true;
} catch (PDOException $e) {
die('PDO cannot connect: '.$e->getMessage());
}
}
public function query($sql) {
if(!isset($this->_connected[self::$active_connection])) $this->connect();
$sql = str_replace('%tp%', self::$tp, $sql);
$stmt = $this->db->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$args = array();
if(func_num_args() > 1) {
$args = func_get_args();
array_shift($args);
$i = 1;
foreach($args as $argument) {
$stmt->bindValue($i, $argument);
$i++;
}
}
$start = microtime(true);
try {
$stmt->execute();
} catch(PDOException $e) {
Error::raise($e->getMessage());
}
$duration = microtime(true) - $start;
if($stmt->errorCode() !== '00000') {
$err = $stmt->errorInfo();
Error::raise('PDO error: '.$err[2]);
}
if(DEBUG) {
$log = array();
$log['query'] = $sql;
$log['duration'] = sprintf("%2.4f s", $duration);
$log['raw'] = $duration;
$trace = debug_backtrace();
$trace = $trace[0];
$log['caller'] = array(
'file' => (!empty($trace['file']) ? str_replace(ROOT_PATH, '', Library::formatPath($trace['file'])) : 'unknown'),
'line' => (!empty($trace['line']) ? $trace['line'] : 'unknown'),
);
self::$querylog[] = $log;
}
return new ResultSet($stmt, $args);
}
public function begin() {
if(!isset($this->_connected[self::$active_connection])) $this->connect();
try {
$this->db->beginTransaction();
} catch(PDOException $e) {
Error::raise('PDO Exception: '.$e->getMessage());
}
}
public function commit() {
if(!isset($this->_connected[self::$active_connection])) $this->connect();
try {
$this->db->commit();
} catch(PDOException $e) {
Error::raise('PDO Exception: '.$e->getMessage());
}
}
public function rollback() {
if(!isset($this->_connected[self::$active_connection])) $this->connect();
try {
$this->db->rollBack();
} catch(PDOException $e) {
Error::raise('PDO Exception: '.$e->getMessage());
}
}
public function insertId() {
return $this->db->lastInsertId();
}
public static function getDebug() {
$output = '';
$total = 0;
foreach(self::$querylog as $key => $log) {
$output .= Library::stringPad($key+1, 2, ' ').") ".$log['duration']. " @ " .$log['caller']['file']. " : " .$log['caller']['line']."n";
$output .= "t".$log['query']."n";
$total += $log['raw'];
}
$output .= "nTotal query time: ".sprintf("%2.4f s", $total);
return $output;
}
public function count($table, $where = '') {
$query = 'SELECT COUNT(*) AS counted FROM %tp%'.$table;
if(!empty($where)) {
$query .= ' WHERE '.$where;
}
$rs = $this->query($query)->fetch();
return $rs['counted'];
}
}
class ResultSet implements Iterator,ArrayAccess {
private $_statement = null;
private $_params = array ();
private $_currentRowObj = null;
private $_currentRowIndex = 0;
public function __construct(PDOStatement $statement, array $params) {
$this->_statement = $statement;
$this->_params = $params;
}
public function refresh() {
$this->_statement->execute($this->_params);
if ($this->_statement->errorCode() !== '00000') {
throw new Exception($this->_statement->errorInfo());
}
}
public function fetch() {
return $this->next();
}
public function fetchAll() {
$this->_currentRowIndex = $this->count() - 1;
return $this->_statement->fetchAll(PDO::FETCH_ASSOC);
}
public function current() {
return $this->_currentRowObj;
}
public function key() {
return $this->_currentRowIndex;
}
public function next() {
$this->_currentRowObj = $this->_statement->fetch(PDO::FETCH_ASSOC);
if ($this->_statement->errorCode() !== '00000') {
throw new Exception($this->_statement->errorInfo());
}
$this->_currentRowIndex ++;
return $this->_currentRowObj;
}
public function rewind() {
$this->refresh();
$this->_currentRowIndex = 0;
$this->_currentRowObj = $this->_statement->fetchObject();
if ($this->_statement->errorCode() !== '00000') {
throw new Exception($this->_statement->errorInfo());
}
}
public function valid() {
return $this->_currentRowObj !== false;
}
public function count() {
return $this->_statement->rowCount();
}
public function rowCount() {
return $this->_statement->rowCount();
}
public function __destruct() {
$this->_statement->closeCursor();
}
public function offsetSet($offset, $value) {
throw new Exception('Cannot modify ResultSet.');
}
public function offsetExists($offset) {
return $offset < $this->_statement->rowCount();
}
public function offsetUnset($offset) {
throw new Exception('Cannot modify ResultSet.');
}
public function offsetGet($offset) {
for($i=0; $i<$offset; $i++) {
$this->next();
}
return $this->current();
}
}

Sign In
Register
Help



MultiQuote