Custom Search

Database Class in PHP5

In PHP5 due to Object Oriented Concepts, the database connection to MySql will be using Object Oriented concept. This tutorial will guide you creating an database class that will connect to Mysql database and retrieve records from them. This tutorial does not cover exception handling in case of any database connection error as will have to write an Exception Handling class to handle database error.

< ?
class database
{
private $connectlink;	//Database Connection Link
private $username = "--database username--";
private $password = "--database password--";
private $database = "--database name--";
private $hostname = "localhost";
private $resultlink;	//Database Result Recordset link
private $rows;		//Stores the rows for the resultset
 
public function __construct() {
	$this->connectlink = mysql_connect($this->hostname,$this->username,$this->password);
	if(!($this->connectlink)) {
		//throw new DatabaseConnectionException("Error Connecting to the Database".mysql_error(),"101");
	}
	else {
		mysql_select_db($this->database);
	}
}
 
public function __destruct() {
	@mysql_close($this->connectlink);
}
 
public function query($sql) {
	$this->resultlink = mysql_query($sql);
	return $this->resultlink;
}
 
public function fetch_rows($result) {
	$rows = array();
	if($result) {
		while($row = mysql_fetch_array($result)) {
			$rows[] = $row;
		}
	}
	else {
		//throw new RetrieveRecordsException("Error Retrieving Records".mysql_error(),"102");
		$rows = null;
	}
	return $rows;
}
}
 
$db = new database();	//Create database object
 
?>

NOTE:
Here i am connecting to MySql database but if we want to connect to other database provider then will have to change the code wherever mysql function code is written.




PHP Code Explanation:

Similar Posts

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

Almost!

The ‘properties’ are per-instance state values, and the ‘object’ has no good way to set them.

They should be settable when constructing, not hard-coded.

Also, they should NOT be settable after constructing.

However, they could be gettable…

can you show how your would use “mysqli” class?

Leave a comment

(required)

(required)