How to create DB class in php

21:07

DB Class

In general we are using PHP mysqli/mysql functions directly when we need to connect database for retrieve or storing data. so when we are using this 'Direct calling mysql' concept to create following problems
  • Code Redundancy

    • Means every time we build and passing the query through mysql/mysqli function when we need to interact with database.In future if any PHP/Mysql functions upgraded then we will change the all code on which pages we are using.
  • Unstructured Format

Using DB Class

So we overcome above problems by using class DB. First include following db class in your application so $conn is acts global variable.

<?php 
class db
{
 
 public $conn='';
 
 public $host='localhost';
 
 public $user = 'root';
 
 public $pass = '';
 
 public $db = 'jobs';
 
 /* This function is used to connect the database */
 
 function __construct()
 {
  try{
   $this->conn = mysqli_connect($this->host,$this->user,$this->pass,$this->db);
  }
  catch(Exception $e)
  {
   echo 'Message: ' .$e->getMessage();
   return;
  }
  
  return $this->conn;
 }
 
 /* This function is used to get selected records from db */
 
 function getRows($sql)
 {
     
  $result=$this->query($sql);
  
  $rows=mysqli_fetch_all($result);
  
  return $rows;
  
 }
 
 
 /* This function is used to get selected records from db */
 
 function getRow($sql)
 {
     
  $result=$this->query($sql);
  
  $rows=mysqli_fetch_assoc($result);
  
  return $rows;
  
 }
 
 /* execute the selected query */
 
 function query($sql)
 {
  return mysqli_query($this->conn,$sql);
 }

}
$conn=new db();
?>
we can easily interact with database by using above class. No need to write mysql/mysqli function every time. Example:
<?php 
//getting rows from jobs table
$rows=$conn->getRows("select * from jobs order by id desc");
if($rows)
{
   foreach($rows as $row)
    {
        //display what we need
    }
}
?>

No comments:

Powered by Blogger.