In this tutorial, we will learn how to fetch data from a database using php and ajax, and previous article we will learn to insert data in the database using php and ajax.
ok, Let's create empty php files,
- config.php
- fetchdata.php
- viewdata.php
Database Table:
CREATE TABLE student (
id int(11) NOT NULL PRIMARY KEY,
name varchar(100) NOT NULL,
email varchar(50) NOT NULL,
mobileno varchar(100) NOT NULL,
city varchar(50) NOT NULL
)
config.php
$hostname = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$hostname;dbname=studentresults", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Database connected successfully";
} catch(PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
CREATE fetchdata.php FILES:
<?php
include 'config.php';
$stmt = $conn->prepare("select * from student");
$stmt->execute();
$fetch = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($fetch as $row)
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['mobileno']; ?></td>
<td><?php echo $row['city']; ?></td>
</tr>
<?php
}
?>
CREATE viewdata.php FILES:
<div class="container py-5">
<h1 class="text-center"> Ajax Fetch Data</h1>
<table class="table table-bordered" >
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Email</th>
<th>Mobile NO</th>
<th>City</th>
</tr>
</thead>
<tbody class="viewdata">
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: "fetchdata.php",
type: "POST",
success: function(data){
$('.viewdata').html(data);
}
});
</script>