Home >>PHP Object Oriented >Fetch data from MySQL using OOP

Fetch data from MySQL using OOP

How to Fetch data from database Using OOPS in php

We have already created a class i.e "Database". Add new fields to admin table like Emailid, Mobile etc and insert data into these fields. Add a new method to this class displayall(), and pass an argument for table name. Connect the database through $this keyword, make a table to get the user's data in a tabular form. then make a sql query to get all records of a user. Start while loop, with the help of $res variable print user's data i.e Username, EmailId, Password & Mobile No.

Database Class and displayall() method

<?php
class Database
{
public function displayall($tbName)
{
$conn=$this->connect();
		
echo "<table border='1'>";
echo "<tr><th>UserName</th><th>Email</th><th>Password</th><th>Mobile</th></tr>";
		
$quer=mysqli_query($conn,"select * from $tbName");
		
while($res=mysqli_fetch_array($quer))
{
echo "<tr>";
echo "<td>".$res['UserName']."</td>";
echo "<td>".$res['Email']."</td>";
echo "<td>".$res['Password']."</td>";
echo "<td>".$res['Mobile']."</td>";
echo "</tr>";
}
echo "</table>";
}		 
}	
?>

Create Object of class database and Call displayall() method

<?php
$obj=new Database();

//here admin is a table name
$obj->displayall("admin");
?>