How to Fetch/Retrieve data from database in php mysql
How to get data from database in php mysql
In this tutorial, you will learn how to get / retrieve data from database in php mysql, so we will create a html table format to fetch data in it using php mysql.
So guys, to fetch data make sure you have created your database & table.
Step 1. Create your database connection in dbconfig.php file:
<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database_name";
// Create DB Connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
Step 2: Create a file index.php and fetch data in it and we are using bootstrap v5 to design the User Interface:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fetch Data in PHP MySQL</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header">
<h4>Fetch data from database in PHP MySQL</h4>
</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Course</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
include('dbconfig.php');
$query = "SELECT * FROM students";
$query_run = mysqli_query($conn, $query);
if(mysqli_num_rows($query_run) > 0) //Atleast 1 record is there or not
{
foreach($query_run as $row)
{
?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['fullname'] ?></td>
<td><?= $row['course'] ?></td>
<td><?= $row['email'] ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="4">No Record Found</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Thanks for reading.
Latest Posts
Create dynamic SQL insert query in php and mysql How to Export MySQL data to excel sheet in PHP How to import excel file into mysql database in PHP How to make Registration / Signup form in php How to upload an image in PHP mysql How to make Login System with Session in PHP MySQL How to Delete data from database in php mysql How to Update Data in MySQL Database in PHP How to Fetch/Retrieve data from database in php mysql How to Insert data into database in php mysql© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT