PHPGurukul

How to Fetch data from database Using OOPS In PHP

This post about how to fetch data from database using oops concept in PHP. In previous post i explained how to insert data using OOPs concepts. Now from the same table we will fetch the data.
View Demo
1.
Create a apge function.php inside this page define a class DB_con.
In DB_con class define a constructer for dbconnection and write a funtion for fetchdata.

<?php
session_start();
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'demos');
class DB_con
{
 function __construct()
 {
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
$this->dbh=$con;
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
 }
 public function fetchdata()
 {
 $result=mysqli_query($this->dbh,"select * from insertdata");
 return $result;
 }
}
?>

2. create a page where you can create a object for class and call the fetchdata function.

<?php
include_once("function.php");
$fetchdata=new DB_con();
 ?>
 <table width="100%"  border="0" >
  <tr>
    <th width="9%" height="42" scope="col" >S no.</th>
    <th width="13%" scope="col">Name</th>
    <th width="11%" scope="col">Email</th>
    <th width="11%" scope="col">Contact no</th>
    <th width="11%" scope="col">Gender</th>
    <th width="13%" scope="col">Education</th>
    <th width="13%" scope="col">Address</th>
    <th width="19%" scope="col">PostingDate</th>
  </tr>
  <?php
  $sql=$fetchdata->fetchdata();
  $cnt=1;
  while($row=mysqli_fetch_array($sql))
  {
  ?>
  <tr>
      <td height="29"><?php echo $cnt;?></td>
    <td><?php echo $row['name'];?></td>
    <td><?php echo $row['email'];?></td>
    <td><?php echo $row['contactno'];?></td>
    <td><?php echo $row['gender'];?></td>
    <td><?php echo $row['education'];?></td>
    <td><?php echo $row['addrss'];?></td>
    <td><?php echo $row['posting_date'];?></td>
  </tr>
  <?php $cnt=$cnt+1;} ?>
</table>

View Demo

Download full Source Code (Fetch Data Using OOPS Concept)
Size: 140 KB
Version: V 1.2

Anuj Kumar

This is Anuj Kumar. I’m a professional web developer with 4+ year experience. I write blogs in my free time. I love to learn new technologies and share with others.
I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials.
.

Recommended Tutorials for you


5 comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.