MySQL Database Interaction PHP Class

There are many ways out there to connect to a database, but there is only a few of them that are effective. This is the MySQL object that I use to connect to a database via PHP. You will find this class to be simple but very effective as it’s not overfilled, but it only contains what it’s needed in order to compile a successful application. I have used it multiple times in tasks that include from basic user managements to custom cloud application development. From connecting to a single database, to multiple databases.

Here is the code, please make sure to replace the values of the variables so that you can successfully connect to your database.

class db
//Object Variables Please Replace, you can also have them set on the constructor so that you can connect to multiple databases.
private $status;
private $host = ‘localhost’;
private $database = ‘db_name’;
private $username = ‘username’;
private $password = ‘password’;
public ξ$result;
public ξ$results;
function __construct(){
//Connect To Database
$this->status = mysql_connect($this->host,$this->username,$this->password) or die (‘Cannot Open Conection to ‘ .
//Select Database
function query($sql){
//Get Results
$this->result = ξmysql_query($sql);
function fetch($sql,$type){
//Perform Query
switch ($type){
//Fetch as an Array
case ‘array’:
$this->results = mysql_fetch_array($this->result);
//Fetch as an Asspciative Array
case ‘assoc’:
$this->results = mysql_fetch_assoc($this->result);
//Fetch as an Object
case ‘object’:
$this->results = mysql_fetch_object($this->result);
//Return Results
return $this->results;
function checkit($sql){
//Check Table for Query
return mysql_num_rows(mysql_query($sql));
function __destruct(){
//Free Query Result
//Close DB Connection

Please let any comments, suggestions orξrecommendationsξon the area below.

Leave a Reply

Your email address will not be published. Required fields are marked *