In this post, we will be learning, how to fetch or retrieve data from database in php using oop (object oriented programming in php) where we will use MySQLi Object Oriented & MySQLi Procedural code to get data.
dbcon.php
<?php
class database{
private $host;
private $db;
private $username;
private $pw;
protected function connect(){
$this->host = 'localhost';
$this->db = 'oops';
$this->username = 'root';
$this->pw = '';
$con = new mysqli($this->host,
$this->username, $this->pw,
$this->db); return $con;
}
}
?>
students.php
<?php
include 'dbcon.php';
class query extends database{
function getData(){
$q = "SELECT * FROM student";
$result = $this->connect()->query($q);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo 'Name : '.$row['name'].' Mobile : '.$row['phone'].'<br/>';
}
}
}
}
$obj = new query;
$obj->getData();
students.php
<div class="container card table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<?php
include 'dbcon.php';
class query extends database{
function getData(){
$q = "SELECT * FROM student";
$result = $this->connect()->query($q);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){ ?>
<tbody>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td>
<a href="edit/<?php echo $row['id']; ?>" class="btn btn-primary">Edit</a>
<a href="delete/<?php echo $row['id']; ?>" class="btn btn-danger">Delete</a>
</td>
</tr>
</tbody>
<?php
} ?>
</table>
</div>
<?php }
}
}
$obj = new query;
$obj->getData();
?>