How to create a Student Management System using React (frontend) and PHP (backend)

Rashmi Mishra
0

How to create a Student Management System using React (frontend) and PHP (backend) :


Step 1: Set Up Your Environment

1.   Install Node.js and npm

o    Download and install Node.js from Node.js official website. npm (Node Package Manager) comes with it.

2.   Install XAMPP

o    Install XAMPP for PHP and MySQL support.


Step 2: Create the Project Structure

1.   Initialize React App

npx create-react-app student-management-system

cd student-management-system

2.   Set Up the Backend

o    Inside the XAMPP htdocs directory, create a folder named student-management-backend.

o    Use this folder for your PHP files.


Step 3: Design the Database

Use phpMyAdmin to create the database:

1.   Create Database: student_management.

2.   Create Tables:

o    students:

 CREATE TABLE students (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(100) NOT NULL,

    phone VARCHAR(15),

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

o    Add additional tables as needed (e.g., classes, attendance).


Step 4: Backend Development (PHP)

1.   Create Connection File: db_connection.php

<?php

$host = 'localhost';

$db = 'student_management';

$user = 'root';

$pass = '';

$conn = new mysqli($host, $user, $pass, $db);

 

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

?>

2.   Create API Endpoints:

o    Get All Students (get_students.php):

<?php

include 'db_connection.php';

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

$students = array();

while ($row = $result->fetch_assoc()) {

    $students[] = $row;

}

echo json_encode($students);

?>

o    Add Student (add_student.php):

<?php

include 'db_connection.php';

$data = json_decode(file_get_contents('php://input'), true);

$name = $data['name'];

$email = $data['email'];

$phone = $data['phone'];

$sql = "INSERT INTO students (name, email, phone) VALUES ('$name', '$email', '$phone')";

if ($conn->query($sql)) {

    echo json_encode(['message' => 'Student added successfully']);

} else {

    echo json_encode(['message' => 'Failed to add student']);

}

?>

o    Similarly, create endpoints for update and delete operations.


Step 5: Frontend Development (React)

1.   Install Axios (for HTTP requests):

npm install axios

2.   Create Components:

o    App Component: Create the main layout.

o    StudentList Component: Fetch and display the list of students.

o    AddStudent Component: Add a form to add new students.

o    EditStudent Component: Update existing student information.

o    DeleteStudent Component: Confirm and delete a student record.

3.   Fetch Students (StudentList Component):

import React, { useState, useEffect } from "react";

import axios from "axios";

 

const StudentList = () => {

    const [students, setStudents] = useState([]);

 

    useEffect(() => {

        axios.get("http://localhost/student-management-backend/get_students.php")

            .then(response => {

                setStudents(response.data);

            })

            .catch(error => {

                console.error("Error fetching students:", error);

            });

    }, []);

 

    return (

        <div>

            <h1>Student List</h1>

            <ul>

                {students.map(student => (

                    <li key={student.id}>

                        {student.name} - {student.email} - {student.phone}

                    </li>

                ))}

            </ul>

        </div>

    );

};

 

export default StudentList;

4.   Add a Student (AddStudent Component):

 

import React, { useState } from "react";

import axios from "axios";

 

const AddStudent = () => {

    const [name, setName] = useState("");

    const [email, setEmail] = useState("");

    const [phone, setPhone] = useState("");

 

    const handleSubmit = (e) => {

        e.preventDefault();

        axios.post("http://localhost/student-management-backend/add_student.php", {

            name,

            email,

            phone

        })

        .then(response => {

            alert(response.data.message);

        })

        .catch(error => {

            console.error("Error adding student:", error);

        });

    };

 

    return (

        <form onSubmit={handleSubmit}>

            <h1>Add Student</h1>

            <input

                type="text"

                placeholder="Name"

                value={name}

                onChange={(e) => setName(e.target.value)}

            />

            <input

                type="email"

                placeholder="Email"

                value={email}

                onChange={(e) => setEmail(e.target.value)}

            />

            <input

                type="text"

                placeholder="Phone"

                value={phone}

                onChange={(e) => setPhone(e.target.value)}

            />

            <button type="submit">Add Student</button>

        </form>

    );

};

 

export default AddStudent;


Step 6: Integrate Frontend and Backend

1.   Run the backend using XAMPP (Apache and MySQL services).

2.   Start the React app:

npm start

3.   Access the React app at http://localhost:3000.


Step 7: Testing and Deployment

1.   Test all functionalities (CRUD operations).

2.   Deploy the frontend using services like Netlify or Vercel.

3.   Deploy the backend and database on a live server.


Additional Features

  • Add authentication for admin and students.
  • Include pagination for large student lists.
  • Implement sorting and filtering options.

Project Structure


1. React (Frontend)

The React application will be located in a folder named student-management-system.

student-management-system/

├── public/

   ├── index.html        # Main HTML file

   ├── favicon.ico       # App icon

├── src/

   ├── components/

      ├── AddStudent.js        # Component to add a student

      ├── EditStudent.js       # Component to edit a student

      ├── StudentList.js       # Component to display students

      ├── DeleteStudent.js     # Component to delete a student

      └── Navbar.js            # Component for navigation bar

   ├── styles/

      └── styles.css           # CSS file for styling

   ├── App.js                   # Main app component

   ├── index.js                 # Entry point

   ├── api/

      └── api.js               # API utility functions (Axios setup)

   ├── constants/

      └── endpoints.js         # Centralized API endpoints

   └── utils/

       └── validation.js        # Utility functions (e.g., form validation)

├── package.json                 # Dependencies and scripts

└── README.md                    # Project documentation


2. PHP (Backend)

The backend PHP files will be stored in the XAMPP htdocs directory inside a folder named student-management-backend.

htdocs/

└── student-management-backend/

    ├── db_connection.php       # Database connection file

    ├── get_students.php        # Endpoint to fetch all students

    ├── add_student.php         # Endpoint to add a student

    ├── edit_student.php        # Endpoint to edit a student

    ├── delete_student.php      # Endpoint to delete a student

    ├── student_management.sql  # Database schema (optional backup)

    ├── config/

       ├── headers.php         # CORS and headers configuration

       └── helpers.php         # Helper functions (e.g., validation)

    ├── logs/

       └── error.log           # Error logging (optional)

    └── README.md               # Backend documentation


3. Database Structure

The database (student_management) will have the following tables:

students

Field

Type

Description

id

INT (PK)

Primary key (auto-increment)

name

VARCHAR(100)

Name of the student

email

VARCHAR(100)

Email of the student

phone

VARCHAR(15)

Phone number

created_at

TIMESTAMP

Timestamp when the record was created

Other tables (optional):

  • classes (if needed for grouping students by class).
  • attendance (if attendance tracking is required).

4. Final Folder Structure

Root Project Structure

project/

├── student-management-system/       # React frontend

├── student-management-backend/      # PHP backend

└── database/

    └── student_management.sql       # Database schema file (optional)

Project Structure

htdocs/

└── student-management-system/       # Main project folder

    ├── backend/                     # PHP Backend

       ├── db_connection.php        # Database connection file

       ├── get_students.php         # Endpoint to fetch all students

       ├── add_student.php          # Endpoint to add a student

       ├── edit_student.php         # Endpoint to edit a student

       ├── delete_student.php       # Endpoint to delete a student

       ├── config/

          ├── headers.php          # CORS and headers configuration

          └── helpers.php          # Helper functions (optional)

       ├── logs/

          └── error.log            # Error log file (optional)

       └── README.md                # Backend documentation

    ├── frontend/                    # React Frontend

       ├── public/                  # Public folder

          ├── index.html           # Main HTML file

          ├── favicon.ico          # App icon

       ├── src/                     # Source files

          ├── components/          # React components

             ├── AddStudent.js        # Component to add a student

             ├── EditStudent.js       # Component to edit a student

             ├── StudentList.js       # Component to display students

             ├── DeleteStudent.js     # Component to delete a student

             └── Navbar.js            # Component for navigation bar

          ├── styles/

             └── styles.css           # CSS file for styling

          ├── App.js                   # Main app component

          ├── index.js                 # Entry point

          ├── api/

             └── api.js               # API utility functions (Axios setup)

          ├── constants/

             └── endpoints.js         # Centralized API endpoints

          └── utils/

              └── validation.js        # Utility functions (e.g., form validation)

       ├── package.json                 # Dependencies and scripts

       ├── package-lock.json            # Lock file for npm dependencies

       └── README.md                    # Frontend documentation

    ├── database/

       └── student_management.sql       # Database schema (optional backup)

    └── README.md                        # Project documentation


Steps to Work with This Structure

1.   React Frontend Development:

o    Navigate to the frontend folder.

o    Run React development server:

cd frontend

npm start

o    During development, use the proxy setting in package.json to point React's requests to the PHP backend:

{

  "proxy": "http://localhost/student-management-system/backend/"

}

2.   PHP Backend Development:

o    Place all PHP files in the backend folder.

o    Access backend endpoints at:

http://localhost/student-management-system/backend/get_students.php

3.   Testing Both Together:

o    Use npm run build in the frontend folder to create a production build.

o    Move the build output to the htdocs/student-management-system/frontend folder.

4.   Database Setup:

o    Import the database schema (student_management.sql) into phpMyAdmin.


Why This Structure Works

  • Frontend and Backend Separation: Keeps React and PHP code organized in separate folders.
  • Ease of Deployment: Both frontend and backend are under the same root folder, making it easier to deploy.
  • Accessible via Localhost: The whole project is accessible under http://localhost/student-management-system/.

The flow of the Student Management System project involves communication between the frontend (React) and the backend (PHP) with a database (MySQL) to perform CRUD operations.


1. Application Flow

Frontend (React)

1.   User Interaction:

o    The user accesses the React application via a web browser.

o    Navigates through various pages using a navigation bar, such as:

§  Student List: Displays all students.

§  Add Student: Form to add a new student.

§  Edit Student: Form to edit student details.

§  Delete Student: Option to delete a student.

2.   API Requests:

o    User actions trigger API requests using Axios or Fetch to communicate with the PHP backend.

o    Examples:

§  Fetch all students: GET /backend/get_students.php

§  Add a student: POST /backend/add_student.php

§  Edit a student: PUT /backend/edit_student.php

§  Delete a student: DELETE /backend/delete_student.php

3.   Dynamic Updates:

o    React dynamically updates the UI based on the API response (e.g., adding a new student refreshes the list).

Backend (PHP)

1.   Request Handling:

o    PHP scripts handle incoming requests from the frontend.

o    For example:

§  get_students.php: Queries the database for student records and sends them as JSON to the frontend.

§  add_student.php: Inserts a new student into the database.

§  edit_student.php: Updates student details in the database.

§  delete_student.php: Deletes a student from the database.

2.   Validation and Error Handling:

o    PHP validates data sent from the frontend.

o    Returns error messages (e.g., "Invalid email format") if data is incorrect.

3.   Database Interaction:

o    PHP interacts with MySQL to perform CRUD operations.

o    Example SQL queries:

§  Select all students:

sql

Copy code

SELECT * FROM students;

§  Insert a new student:

sql

Copy code

INSERT INTO students (name, email, phone) VALUES ('John Doe', 'john@example.com', '1234567890');

Database (MySQL)

  • Stores all data, such as:
    • Student information: id, name, email, phone, created_at.
    • Optional additional tables (e.g., classes for grouping students, attendance for tracking).

2. Detailed Flow Steps

1.   Fetching Students:

o    User opens the app; React sends a GET request to get_students.php.

o    PHP retrieves the list of students from MySQL and sends it as JSON.

o    React displays the list in the StudentList.js component.

2.   Adding a Student:

o    User clicks Add Student and fills out a form.

o    Form data is sent via a POST request to add_student.php.

o    PHP validates the data and inserts it into the students table.

o    React refreshes the list to show the newly added student.

3.   Editing a Student:

o    User clicks the Edit button next to a student’s name.

o    Pre-filled data is displayed in a form.

o    User updates the details and submits the form.

o    Data is sent via a PUT request to edit_student.php.

o    PHP updates the corresponding record in MySQL.

o    React updates the list dynamically.

4.   Deleting a Student:

o    User clicks the Delete button.

o    React sends a DELETE request to delete_student.php with the student’s ID.

o    PHP deletes the student from the students table.

o    React removes the student from the list.


3. High-Level Diagram

User <--> React Frontend <--> PHP Backend <--> MySQL Database


4. Workflow

1.   Frontend:

o    User Interface for interactions (React Components).

o    Sends API requests to the backend.

o    Receives responses and updates the UI.

2.   Backend:

o    Handles API requests (CRUD operations).

o    Validates input and processes data.

o    Interacts with the database.

3.   Database:

o    Stores student data persistently.

o    Handles queries from the backend.


5. Example User Journey

Scenario: A user wants to add a new student.

1.   The user clicks on the Add Student button in the React app.

2.   Fills in the form with the student’s details and submits.

3.   React sends the form data via a POST request to the PHP add_student.php script.

4.   PHP validates the input and inserts the data into the students table in MySQL.

5.   A success response is sent back to React.

6.   React refreshes the list and shows the new student.


API Workflow

1.   Frontend (React):

o    Uses HTTP requests (GET, POST, PUT, DELETE) to interact with PHP APIs.

o    Axios or Fetch is commonly used to make these requests.

o    Example:

// Example with Axios

import axios from "axios";

 

const fetchStudents = async () => {

    const response = await axios.get("http://localhost/student-management-system/backend/get_students.php");

    return response.data;

};

2.   Backend (PHP):

o    PHP scripts act as API endpoints, responding to frontend requests.

o    Process input data, interact with the MySQL database, and return JSON responses.

o    Example:

// get_students.php

header("Content-Type: application/json");

 

include "db_connection.php";

 

$query = "SELECT * FROM students";

$result = $conn->query($query);

 

$students = array();

while ($row = $result->fetch_assoc()) {

    $students[] = $row;

}

 

echo json_encode($students);

3.   Database (MySQL):

o    Stores and retrieves data as requested by the PHP backend.

o    Queries are executed securely using prepared statements.


API Endpoints

Here’s a list of API endpoints you need to implement for the student management system:

1. Get All Students

  • Endpoint: /backend/get_students.php
  • Method: GET
  • Description: Fetch all student records from the database.
  • Response Example:

 [

  { "id": 1, "name": "John Doe", "email": "john@example.com" },

  { "id": 2, "name": "Jane Smith", "email": "jane@example.com" }

]

2. Add a New Student

  • Endpoint: /backend/add_student.php
  • Method: POST
  • Description: Add a new student to the database.
  • Request Body:

{ "name": "John Doe", "email": "john@example.com", "phone": "1234567890" }

  • Response Example:

{ "status": "success", "message": "Student added successfully." }

3. Edit a Student

  • Endpoint: /backend/edit_student.php
  • Method: PUT
  • Description: Update an existing student's details.
  • Request Body:

{ "id": 1, "name": "John Updated", "email": "john.updated@example.com" }

  • Response Example:

{ "status": "success", "message": "Student updated successfully." }

4. Delete a Student

  • Endpoint: /backend/delete_student.php
  • Method: DELETE
  • Description: Delete a student by ID.
  • Request Body:

{ "id": 1 }

  • Response Example:

{ "status": "success", "message": "Student deleted successfully." }


Setting Up API in PHP

1.   Database Connection File (db_connection.php):

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "student_management";

 

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

 

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

?>

2.   API Example: Add a Student (add_student.php):

<?php

header("Content-Type: application/json");

include "db_connection.php";

 

// Get JSON input

$data = json_decode(file_get_contents("php://input"), true);

 

$name = $data["name"];

$email = $data["email"];

$phone = $data["phone"];

 

$query = $conn->prepare("INSERT INTO students (name, email, phone) VALUES (?, ?, ?)");

$query->bind_param("sss", $name, $email, $phone);

 

if ($query->execute()) {

    echo json_encode(["status" => "success", "message" => "Student added successfully."]);

} else {

    echo json_encode(["status" => "error", "message" => "Error adding student."]);

}

?>


API Integration in React

1.   API Utility File (api.js):

import axios from "axios";

 

const API_BASE_URL = "http://localhost/student-management-system/backend/";

 

export const fetchStudents = () => axios.get(`${API_BASE_URL}get_students.php`);

export const addStudent = (student) => axios.post(`${API_BASE_URL}add_student.php`, student);

export const editStudent = (student) => axios.put(`${API_BASE_URL}edit_student.php`, student);

export const deleteStudent = (id) => axios.delete(`${API_BASE_URL}delete_student.php`, { data: { id } });

2.   React Component Example:

import React, { useEffect, useState } from "react";

import { fetchStudents } from "./api";

 

const StudentList = () => {

    const [students, setStudents] = useState([]);

 

    useEffect(() => {

        fetchStudents()

            .then(response => setStudents(response.data))

            .catch(error => console.error("Error fetching students:", error));

    }, []);

 

    return (

        <div>

            <h1>Student List</h1>

            <ul>

                {students.map(student => (

                    <li key={student.id}>

                        {student.name} - {student.email}

                    </li>

                ))}

            </ul>

        </div>

    );

};

 

export default StudentList;


Flow Summary

1.   User interacts with the React frontend.

2.   React sends API requests to PHP backend (via Axios or Fetch).

3.   PHP processes the request, interacts with the database, and returns a JSON response.

4.   React updates the UI dynamically based on the response.

 


Post a Comment

0Comments

Post a Comment (0)