Fetch Records in PHP and React Js with Pagination

Fetch Records in PHP with ReactJS from MySQL with Pagination and Search

In today’s digital era, web developers often face the challenge of retrieving data from a MySQL database and displaying it dynamically on a webpage. This becomes even more complex when incorporating technologies like PHP and ReactJS. In this article, we will explore how to fetch records from a MySQL database using PHP, integrate it with ReactJS, and implement pagination and search functionality for an enhanced user experience.

1. Introduction

As web applications become more interactive and data-driven, it is crucial to have efficient mechanisms to retrieve data from databases and present it to users. PHP, a popular server-side scripting language, and ReactJS, a JavaScript library for building user interfaces, offer a powerful combination to achieve this goal. By leveraging PHP’s database connectivity and ReactJS’s dynamic rendering capabilities, we can create seamless user experiences.

2. Understanding PHP and ReactJS

Before diving into the implementation details, let’s briefly understand PHP and ReactJS.
PHP is a server-side scripting language designed for web development. It is widely used for its simplicity, scalability, and extensive database connectivity capabilities. PHP can interact with various databases, including MySQL, to fetch, manipulate, and store data.
ReactJS, on the other hand, is a JavaScript library maintained by Facebook. It simplifies the process of building interactive user interfaces by breaking them down into reusable components. ReactJS efficiently updates and renders components based on changes in data, resulting in fast and responsive web applications.

3. Connecting PHP and MySQL

To begin fetching records from a MySQL database using PHP, we need to establish a connection between the two. First, ensure that you have a MySQL database set up and the necessary credentials at hand.
In PHP, we can use the MySQLi extension or PDO (PHP Data Objects) to connect to the database. Both options provide secure and efficient methods for database connectivity. Choose the approach that aligns with your project requirements and preferences.

4. Fetching Records from MySQL Database

Setting up the database connection
To connect to the MySQL database from PHP, we need to provide the appropriate credentials and establish a connection object. Here’s an example of connecting using MySQLi:
php
<?php
$servername = “localhost”;
$username = “your_username”;
$password = “your_password”;
$database = “your_database”;
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully”;
?>
Writing the PHP script to fetch records
Once the connection is established, we can proceed to fetch records from the database. Suppose we have a table named “users” with columns such as “id,” “name,” and “email.” Here’s an example PHP script to fetch records from the “users” table:
php
<?php
$sql = “SELECT * FROM users”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo “ID: ” . $row[“id”] . ” – Name: ” . $row[“name”] . ” – Email: ” . $row[“email”] . “<br>”;
    }
} else {
    echo “No records found.”;
}
$conn->close();
?>

5. Displaying Records in ReactJS

Now that we can fetch records from the MySQL database using PHP, let’s integrate it with ReactJS to display the data on a webpage.
Setting up the ReactJS environment
Before we begin, ensure you have Node.js and npm (Node Package Manager) installed on your machine. Create a new ReactJS project using the following command:
npx create-react-app my-app
Once the project is set up, navigate to the project directory using the terminal:
cd my-app
Creating a component to display records
In ReactJS, components are the building blocks of user interfaces. Let’s create a new component called “UserList” to display the fetched records. Open the “src” directory and create a new file named “UserList.js” with the following content:
jsx
import React, { useEffect, useState } from ‘react’;
import axios from ‘axios’;
const UserList = () => {
  const [users, setUsers] = useState([]);
  useEffect(() => {
    axios.get(‘/api/fetch-users.php’)
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);
  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            ID: {user.id} – Name: {user.name} – Email: {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
};
export default UserList;

Fetching records from PHP script using Axios

In the above component, we use the Axios library to make an HTTP GET request to a PHP script, which we’ll create shortly. The PHP script should return the fetched records in JSON format. The useEffect hook ensures that the data is fetched when the component mounts.
To install Axios, run the following command in the terminal:

npm install axios

6. Implementing Pagination

When dealing with a large dataset, it is crucial to implement pagination to improve performance and user experience. Let’s enhance our PHP script and ReactJS component to support pagination.
Adding pagination functionality to the PHP script
To implement pagination, we need to modify our PHP script to retrieve a subset of records based on the requested page number and number of records per page. Here’s an updated version of the PHP script:
php
<?php
$page = $_GET[‘page’] ?? 1; // Current page number
$recordsPerPage = 10; // Number of records to display per page
$offset = ($page – 1) * $recordsPerPage;
$sql = “SELECT * FROM users LIMIT $offset, $recordsPerPage”;
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $response[] = $row;
    }
}
header(‘Content-Type: application/json’);
echo json_encode($response);
$conn->close();
?>

Updating the ReactJS component for pagination

In the ReactJS component, we can add pagination controls and update the API endpoint to include the current page number. Here’s an updated version of the “UserList” component:
jsx
import React, { useEffect, useState } from ‘react’;
import axios from ‘axios’;
const UserList = () => {
  const [users, setUsers] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  useEffect(() => {
    axios.get(`/api/fetch-users.php?page=${currentPage}`)
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, [currentPage]);
  const handlePreviousPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage – 1);
    }
  };
  const handleNextPage = () => {
    setCurrentPage(currentPage + 1);
  };
  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            ID: {user.id} – Name: {user.name} – Email: {user.email}
          </li>
        ))}
      </ul>
      <button onClick={handlePreviousPage} disabled={currentPage === 1}>
        Previous Page
      </button>
      <button onClick={handleNextPage}>
        Next Page
      </button>
    </div>
  );
};
export default UserList;

7. Implementing Search Functionality

To enhance the user experience further, we can implement search functionality to allow users to find specific records based on their search queries. Let’s modify our PHP script and ReactJS component to support this feature.
Creating a search input field in ReactJS
In the “UserList” component, let’s add a search input field to capture the user’s search query. Here’s an updated version of the component:
jsx
import React, { useEffect, useState } from ‘react’;
import axios from ‘axios’;
const UserList = () => {
  const [users, setUsers] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState(”);
  useEffect(() => {
    axios.get(`/api/fetch-users.php?page=${currentPage}&search=${searchQuery}`)
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, [currentPage, searchQuery]);
  // …
  const handleSearch = event => {
    setSearchQuery(event.target.value);
    setCurrentPage(1);
  };
  return (
    <div>
      <h2>User List</h2>
      <input type=”text” value={searchQuery} onChange={handleSearch} placeholder=”Search by name or email” />
      {/* Rest of the code */}
    </div>
  );
};
export default UserList;

Modifying the PHP script for search functionality

In the PHP script, we can update the SQL query to include the search functionality. Here’s an updated version of the script:
php
Copy code
<?php
$page = $_GET[‘page’] ?? 1;
$recordsPerPage = 10;
$search = $_GET[‘search’] ?? ”;
$offset = ($page – 1) * $recordsPerPage;
$sql = “SELECT * FROM users WHERE name LIKE ‘%$search%’ OR email LIKE ‘%$search%’ LIMIT $offset, $recordsPerPage”;
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $response[] = $row;
    }
}
header(‘Content-Type: application/json’);
echo json_encode($response);
$conn->close();
?>

Updating the ReactJS component for search functionality

In the ReactJS component, we already added the search input field. The input value is stored in the “searchQuery” state variable, which is included in the API endpoint for fetching records. This ensures that the PHP script filters records based on the user’s search query.

8. Conclusion

In this article, we explored how to fetch records from a MySQL database using PHP and display them in a ReactJS application. We learned how to establish a database connection in PHP, fetch records using SQL queries, and render them in a ReactJS component. Additionally, we implemented pagination and search functionality to enhance the user experience.
By leveraging the power of PHP and ReactJS, you can create dynamic web applications that retrieve and present data from a MySQL database efficiently. This opens up endless possibilities for building interactive and data-driven websites.

9. FAQs

Q1: Can I use a different database instead of MySQL with PHP and ReactJS?
PHP has built-in support for various databases, including MySQL, PostgreSQL, SQLite, and more. You can modify the database connection details and SQL queries accordingly to work with your preferred database.
Q2: How can I improve the performance when fetching a large number of records from the database?
To improve performance, you can implement techniques like pagination and limit the number of records fetched per page. This helps reduce the load on the server and improves the response time. Additionally, consider optimizing your SQL queries and database indexes for faster data retrieval.
Q3: Is it possible to implement additional filters along with search functionality?
Yes, you can extend the search functionality to include additional filters. For example, you can add dropdown menus or checkboxes to allow users to filter records based on specific criteria. Modify the SQL query in the PHP script accordingly to accommodate the additional filters.
Q4: Can I use a different front-end framework instead of ReactJS with PHP?
Yes, you are not limited to using ReactJS as the front-end framework. PHP can work seamlessly with other front-end frameworks like Angular, Vue.js, or even traditional HTML, CSS, and JavaScript. Adapt the code examples and API communication methods based on your chosen framework.
Q5: Is it necessary to sanitize user inputs when using PHP and MySQL?
Yes, it is essential to sanitize and validate user inputs to prevent security vulnerabilities like SQL injection. PHP provides functions like mysqli_real_escape_string or prepared statements to sanitize user inputs before incorporating them into SQL queries. Always prioritize security when handling user data.

Leave a Reply

Your email address will not be published. Required fields are marked *