My Main Blog

Tuesday 4 November 2014

Access mysql data using Class in PHP

Access mysql data using Class in PHP using mysql_connect and use mysql_select_db and mysql_query



Access mysql record by Object oriented method using class and object in PHP. Here is the class name is "DBClient" and it's method name is "getDistrict", that is show records from mysql table name "district_names". The __construct() method automatically called when we create any object of class "DBClient".


<?php
class DBClient{
var $host;
var $db ;
var $user;
var $pass;
var $link,$isDBConnect;
var $isError,$errorValue;
function __construct() {
$this->host = "localhost";
$this->db = "dbname";
$this->user = "root"; 
$this->pass = ""; 
try {
$this->link = mysql_connect($this->host, $this->user, $this->pass);
if (!is_resource($this->link)) {
$this->isDBConnect=false;
}
else {
    mysql_select_db($this->db,$this->link);
$this->isDBConnect=true;
}
}
catch(Exception $ee){
$this->link=false;
   $this->isDBConnect=false;
}
}
public function exeQuery($query) {
try {
$result = mysql_query($query, $this->link);
return $result;
}
catch(Exception $ee){
return (FALSE);
}
}
public function getDistrict() {
 $res=false;
 try {
  $sSql="SELECT * FROM district_names";
  $res=$this->exeQuery($sSql);
  $rows = mysql_num_rows($res);
  if($rows>0) {
  } else {
$res=false;
  } 
 } catch(Exception $ee){
  $res=false; 
 } 
 return $res; 
}
}

$dd=new DBClient();
$cntDis=$dd->getDistrict();
if($cntDis) {
while($cntRow=mysql_fetch_array($cntDis)) {
$district_id= $cntRow['district_id'];
$districtname=$cntRow['districtname'];
echo $district_id.'====='.$districtname;
}
 }
?>

2 comments:

  1. Thanks.
    Can you please post code for Showing Exam results when enter a index number?

    ReplyDelete
    Replies
    1. Hi, Just add below method in DBClient class:


      public function getDistrictById($id){
      $res=false;
      try {
      $sSql="SELECT * FROM district_names where dis_id=".$id;
      $res=$this->exeQuery($sSql);
      $rows = mysql_num_rows($res);
      if($rows>0) {
      } else {
      $res=false;
      }
      } catch(Exception $ee){
      $res=false;
      }
      return $res;
      }

      ---------------------------------------------------

      and use it as below:

      $cntDis=$dd->getDistrictById(1234);
      if($cntDis) {
      while($cntRow=mysql_fetch_array($cntDis)) {
      $district_id= $cntRow['district_id'];
      $districtname=$cntRow['districtname'];
      echo $district_id.'====='.$districtname;
      }
      }

      Delete