Please Check My MySQLi Class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ChrisBull
Forum Commoner
Posts: 42
Joined: Fri Aug 20, 2010 7:43 am

Please Check My MySQLi Class

Post 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
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Please Check My MySQLi Class

Post 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 :)
ChrisBull
Forum Commoner
Posts: 42
Joined: Fri Aug 20, 2010 7:43 am

Re: Please Check My MySQLi Class

Post 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.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Please Check My MySQLi Class

Post 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');
Post Reply