Page 1 of 1

Please Check My MySQLi Class

Posted: Fri Aug 27, 2010 6:42 pm
by ChrisBull
I have tried to create a basic class that will connect to mysql using mysqli.

The idea is that another class will you this code to connect to the database and then run some queries.

Code: Select all

$dbConnection = new dbConnection("attributes");
$isConnected = $dbConnection->connectToDB();
This is the class.

Code: Select all

class dbConnection
{
	private $_hostName;
	private $_userName;
	private $_userPassowrd;
	private $_dbName;
	
	private $_dbConnection;
	
	public function __construct($hostName, $userName, $userPassword, $dbName) 
	{
		$this->_hostName          = $hostName;
		$this->_userName          = $userName;
		$this->_userPassword      = $userPassword;
		$this->_dbName            = $dbName;
	}
	
	public function connectToDB() 
	{
		$this->_dbConnection = new mysqli($this->_hostName, $this->_userName, $this->_userPassword, $this->_dbName);
		
		return ($this->_dbConnection) ? true : false;
	}	
		
}
I haven't tested it yet, i just wanted some advise on how to improve it.

Many Thanks For Your time.
Chris

Re: Please Check My MySQLi Class

Posted: Fri Aug 27, 2010 6:51 pm
by Jonah Bron
I'm confused as to it's purpose; It doesn't really reduce code. Normally it only takes one line of code to setup a DB connection.

The code does look nice though :)

Re: Please Check My MySQLi Class

Posted: Sat Aug 28, 2010 2:43 am
by ChrisBull
Lol, i know, it's not finished. I need help on getting it to error report if database connections don't work. Also i will be adding some query functions in later.

Re: Please Check My MySQLi Class

Posted: Sat Aug 28, 2010 7:04 pm
by Jonah Bron
I think it would be best to put connectToDB into __construct; It seems unnecessary to put that into another function. Add a SELECT DB function too. Another handy feature is to return $this on most functions: that enables you to daisy-chain function calls like this:

Code: Select all

$db->selectDB('somedb')->query('SELECT should_panic FROM galaxy_guide WHERE probability = 42');