PHP,MySQL - CLASS BASED DATABASE CONNECTION
An Object Oriented approach to establlishing and managing database connections.
Here I used MySQL Database for Integrating with PHP Scripting (because the famouse combination).
The class “Profile” is a wrapper for developing our PHP database connection.
var $error=”;
var $link;
// Establish Database connection while creating Objects
function __construct($dbhost,$dbuser,$dbpass,$dbase){
$this->link=mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbase);
}
function addData($pid,$uname,$dob) {
global $link;
// Insert data to database
$sql = ‘INSERT INTO `profile` (`pid`, `uname`, `dob`) VALUES (\”.$pid.’\', \”.$uname.’\', \”.$dob.’\');’;
// Execute SQL query
$res=mysql_query($sql);
// Check for Erorrs
if(!$res){
$this->error.=”Profile insertion failed.”.mysql_error();
return 0;
}
if(mysql_affected_rows()<1){
$this->error.=”No rows affected”;
return 0;
}
return 1;
}
// Call destructor for de-link MySQL connection at Object
function __destructor(){
mysql_close($this->link);
}
}
In your coding create an Object for the class Profile with parameters of,
- $dbname - Database host name (example, localhost, yourdomain.com, sub.mydomain.com .. ).
- $dbuser - Database Username ( the user already exists with required privileges).
- $dbpass - Password for that username.
- $dbase - Which is “Database name” to be used for importing tables,passing queries, calling procedures.
The class methods “__construct” and “__destructor” use in PHP:
I used a default constructor for establishing database connection from the arguments received while creating objects,
$pro_obj=new Profile(”localhost”,”myuser”,”mypass”,”db_users”);
- The above oneline code creates an object “$pro_obj” for the class “Profile” at the same time it established a default connection with MySQL Database.
- The method “AddData” in class Profile, used for passing queries to database (db_users).
- At last line the destructor method __destructor delinks the established connection while the object($pro_obj) removed from memory.
