Javascript

How to Fetch Data From Database Using Ajax in PHP

Javascript

How to Fetch Data From Database Using Ajax in PHP

In modern web development, Ajax (Asynchronous JavaScript and XML) plays a crucial role in fetching data from a server without refreshing the entire page. In this tutorial, we'll guide you through the process of fetching data from a MySQL database using Ajax, PHP, and a user table as an example. Let's dive in!

Step 1: Set Up the Database 
First, create a MySQL database and a user table to store user information. Here's an example of creating a table named users with columns for id, name, email, and age:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50),
  email VARCHAR(50),
  age INT
);

Step 2: Create the HTML Structure 
Next, create an HTML structure that will display the fetched data. For example, you can have a table with placeholders for the user data:

<!DOCTYPE html>
<html>
<head>
  <title>User Data</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $.ajax({
        url: "fetch_data.php",
        type: "GET",
        success: function(data) {
          // Update the table with the fetched data
          $("#userTable").html(data);
        }
      });
    });
  </script>
</head>
<body>
  <h1>User Data</h1>
  <table id="userTable">
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Age</th>
    </tr>
  </table>
</body>
</html>

Step 3: Create the PHP Script 
Create a PHP script (fetch_data.php) that will fetch the user data from the database and return it as HTML. Here's an example of fetching the data and generating the HTML table rows:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row["id"] . "</td>";
        echo "<td>" . $row["name"] . "</td>";
        echo "<td>" . $row["email"] . "</td>";
        echo "<td>" . $row["age"] . "</td>";
        echo "</tr>";
    }
} else {
    echo "<tr><td colspan='4'>No users found.</td></tr>";
}

$conn->close();
?>

Step 4: Run the Application 
Save the HTML file with a .html extension and the PHP script with a .php extension. Place both files in your web server's document root directory. Start your web server and access the HTML file through your browser. The user data will be fetched from the database using Ajax and displayed in the table.