Page 1 of 1

Mysql Class with error handling

Posted: Fri Jun 15, 2007 12:17 pm
by staar2

Code: Select all

class RMysql {
    private $_connection;
    private $_result;
    
	public function __construct($host, $user, $pass, $database) {
	    $this->_connection = mysql_connect($host, $user, $pass);
        
        if (!is_resource($this->_connection))
            throw new RMysqlException('Problems with connecting', 1);						   
	    mysql_select_db($database, $this->_connection);	
	    
	}
     
	
	public function query($query) {        
        $this->_result = mysql_query($query);
        
        if (!is_resource($this->_result))
            throw new RMysqlException('Query problem '. $query, 1);
        
        if (!$this->_result)
            throw new RMysqlException('There were problem with returning result', 1);                   
	}
    
    public function getData() {
        return $this->_result;
    }  
	
	public function close() {
	   mysql_free_result($this->_result);
	   mysql_close($this->_connection);    
    }
}

class RMysqlException extends Exception {
    
    public function __construct($message, $code) {
        parent::__construct($message, $code);
    }
    
    public function printError() {
        echo
            "<div>
                <p>Code : ". parent::getCode() ."</p>
            	<p>Error on line: ". parent::getLine() ."</p>
            	<p>Filename: ". parent::getFile() ."</p>	
            	<p>Message: ". parent::getMessage() ."</p>
            </div>";
        exit();
    }
}
And here is example

Code: Select all

define(DEBUG, 1); //Change value here if you dont want to debug

try {
    $new = new RMysql('localhost', 'root', '', 'mysql');
    $new->query('SHOW TABLES');
    
    while ($row = mysql_fetch_row($new->getData())) {
    	echo $row[0] . ' ' . $row[1] . '<br />'; 
    }
    $new->close(); //Close current connection and free result
    
} catch (RMysqlException $e) {
    if ($e->getCode() == 1 && DEBUG == 1) 
        $e->printError();
    else
        echo 'There were some error !'; //Could add here some mail function to admin
}

Posted: Fri Jun 15, 2007 4:43 pm
by feyd
Care you specify what you're looking for feedback in ... or explain the class, its purpose for you, etc etc etc... anything?

Posted: Sat Jun 16, 2007 3:34 am
by staar2
Sorry, forgot to explain :oops:. This is my first mysql handler script which use the Exception handling system. But with exception handling went code slower. Should i use die function, it should be faster? One more thing about class design, I wanted to make that, the RMysql is parent class(abstract class) and add sub classes to fetch data ? I haven't much experience on OOP, if you see something wrong in code, please tell.

Thank You!