How to fetch data from a database using Php Ajax

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.


fetch data from a database using php 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


$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:

include 'config.php'; 
$stmt = $conn->prepare("select * from student");
$fetch = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($fetch as $row)
<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>


CREATE viewdata.php FILES:

<div class="container py-5">
<h1 class="text-center"> Ajax Fetch Data</h1>
<table class="table table-bordered" >
<th>Mobile NO</th>
<tbody class="viewdata">

<script src=""></script>
		url: "fetchdata.php",
		type: "POST",
		success: function(data){

fetch data from database using php ajax
Previous Post Next Post