|
Database Connection Class (PHP/MYSQL) |
|
|
|
|
I wanted a seperate php based database class for a project recently. The requirement was this class should be able to return the results set everytime I pass a MySql query into it. Thought of sharing this code and someone with the same requirement can use this class to get done all the database handling inside codes. Improvements for the class are most welcome.
<?php
class DBConnect
{
private $host = "localhost";//hostname
private $database = "database_name";//database name
private $username = "database_username";//database username
private $password = "database password";//database password
private $link;
private $result;
public $sql;
function __construct($database="")
{
if (!empty($database))
{
$this->database = $database;
}
$this->link = mysql_connect($this->host, $this->username, $this->password);
if (!($this->link))
{
echo mysql_error();
exit;
}
if (!mysql_select_db($this->database))
{
echo mysql_error();
exit;
}
}
function query($sql)
{
if (!empty($sql))
{
$this->sql = $sql;
$this->result = mysql_query($sql);
if ($this->result)
{
return $this->result;
}
else
{
return mysql_error();
}
}
else
{
return false;
}
}
function __destruct()
{
mysql_close();
}
}
$objDBConnect = new DBConnect();
$sql = "SELECT * FROM `table_name`";//sql query
$objDBConnect->query($sql);
?>
Trackback(0)
 |