In this tutorial, I'll cover how you can create a simple PHP MySQLi CRUD application using React JS. Scroll down to the end of the page to you can see the YouTube video(CodeAT21) and GitHub repository full source code available for this.

Setup

First, we'll create the react project and install the two npm packages. In open your system terminal/command line enter the code below :

npx create-react-app context-api
cd context-api
npm install --save react-router-dom
npm install axios
npm start 

Next, Project structure your folder as follows.

context-api/src
├── components
  ├── AddForm.js
  ├── Dashboard.js
  ├── EditForm.js
  ├── Home.js
  └── ListAll.js
├── contexts
  └── MyContext.js
├── App.js
├── index.css
└── index.js 

Next, open up the App.js file located in the src folder. You should see this:

App.js
import React from 'react'; import MyContextProvider from './contexts/MyContext'; import Dashboard from './components/Dashboard'; function App() { return (<MyContextProvider><Dashboard/></MyContextProvider>);} export default App;
Dashboard.js
import React from 'react'; import {BrowserRouter as Router,Switch,Route} from "react-router-dom"; import Home from './Home'; import AddForm from './AddForm'; import EditForm from './EditForm'; function Dashboard() { return ( <div className="App"> <Router basename="/"> <Switch> <Route exact path="/" component={Home}/> <Route exact path="/AddForm" component={AddForm}/> <Route exact path="/EditForm/:EditID" component={EditForm}/> </Switch> </Router> </div> ); } export default Dashboard;
Home.js
import React from 'react'; import {Link} from "react-router-dom"; import ListAll from "./ListAll"; const Home = () => { return ( <div> <h1>React JS and PHP MySQLi CRUD application with React Context API</h1> <div className="wrapper"> <section className="left-side"> <Link to={`/AddForm`}> Add New </Link> </section> <section className="right-side"> <ListAll /> </section> </div> </div> ) } export default Home
AddForm.js
import React,{useContext,useState} from 'react'; import { MyContext } from '../contexts/MyContext'; import { useHistory } from "react-router-dom"; const AddForm = () => { let history = useHistory(); const { insertUser } = useContext(MyContext); const [userInfo, setuserInfo] = useState({ name: '', email: '', }); const onChangeValue = (e) => { setuserInfo({ ...userInfo, [e.target.name]:e.target.value }); } // Inserting a new user into the Database. const submitUser = async(event) => { try { event.preventDefault(); event.persist(); const data = await insertUser(userInfo); if(data.success === true){ history.push(`/`); event.target.reset(); return; } } catch (error) { throw error;} }; return ( <form className="insertForm" onSubmit={submitUser}> <h2> Add Form </h2> <label htmlFor="_name">Name</label> <input type="text" id="_name" name="name" onChange={onChangeValue} placeholder="Enter name" autoComplete="off" required /> <label htmlFor="_email">Email</label> <input type="email" id="_email" name="email" onChange={onChangeValue} placeholder="Enter email" autoComplete="off" required /> <input type="submit" value="Insert" /> </form> ); }; export default AddForm;
ListAll.js
import React,{useContext,useState,useEffect} from 'react'; import { MyContext } from '../contexts/MyContext'; import { Link } from "react-router-dom"; const ListAll = () => { const {userlistall,deleteUserall} = useContext(MyContext); useEffect( () => { window.scrollTo(0, 0); alluser(); }, []); const [isuser, setuser] = useState([]); const alluser = async (ids) => { try { const alluserpreview = await userlistall(ids); console.log(alluserpreview); if(alluserpreview.success === true){ setuser(alluserpreview.fetchusers); } } catch (error) { throw error;} } const deleteConfirm = (id) => { if (window.confirm("Are you sure?")) { deleteUser(id); } }; const deleteUser = async (id) => { try { const deleteUserlist = await deleteUserall(id); if(deleteUserlist.success === true){ setuser([]); alluser(); } } catch (error) { throw error;} } return ( <> {isuser.map((item,index)=>( <div className="list" key={item.id}> <p>Name: {item.user_name}</p> <p>Email: {item.user_email}</p> <Link to={`EditForm/${item.id}`} className="btn default-btn"> Edit </Link> <button className="btn red-btn" onClick={() => deleteConfirm(item.id)}> Delete </button> </div> ))} </> ); }; export default ListAll;
MyContext.js
import React, { createContext,Component } from "react"; import axios from 'axios'; export const MyContext = createContext(); // Define the base URL const Axios = axios.create({ baseURL: 'http://localhost/api/', }); class MyContextProvider extends Component{ userlistall = async () => { const userlistalls = await Axios.get(`client-all.php`); return userlistalls.data; } deleteUserall = async (id) => { const deleteUseralls = await Axios.post(`client-delete.php`,{ userid: id, }); return deleteUseralls.data; } insertUser = async (userInfo) => { const insertUsers = await Axios.post(`client-add.php`,{ name: userInfo.name, email: userInfo.email, }); return insertUsers.data; } fetchUserall = async (id) => { const fetchUseralls = await Axios.post(`client-edit.php`,{ userid: id, }); return fetchUseralls.data; } updateUser = async (userInfo,id) => { const updateUsers = await Axios.post(`client-update.php`,{ name: userInfo.name, email: userInfo.email, userid: id, }); return updateUsers.data; } render(){ const contextValue = { userlistall:this.userlistall, deleteUserall:this.deleteUserall, insertUser:this.insertUser, fetchUserall:this.fetchUserall, updateUser:this.updateUser, } return( <MyContext.Provider value={contextValue}> {this.props.children} </MyContext.Provider> ) } } export default MyContextProvider;

MySQL Database Setup for PHP

In the following example, we will see how to create a Database to make a PHP MySQLi database connection with the Database.

  • Database Name – codeat21
  • Table Name – users
CREATE TABLE users (
   id int(11) NOT NULL AUTO_INCREMENT,
   user_name varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
   user_email varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
    PRIMARY KEY (id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
 

Next, Mysqli Project structure your folder as follows.

xampp\htdocs\api
├── db_connection.php
├── client-add.php
├── client-all.php
├── client-update.php
└── client-delete.php 

mysqli_connect– /db_connection.php is for connecting to database.

db_connection.php
<?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: access"); header("Access-Control-Allow-Methods: POST"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); $db_conn = mysqli_connect("localhost", "root", "", "codeat21"); // Check connection if($db_conn === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } error_reporting(E_ALL); ini_set('display_errors','Off'); ?>

POST – /client-add.php is for inserting new user.

Required Fields – user_name, user_email

client-add.php
<?php require 'db_connection.php'; $data = json_decode(file_get_contents("php://input")); if(isset($data->name) && isset($data->email) && !empty(trim($data->name)) && !empty(trim($data->email)) ){ $name = mysqli_real_escape_string($db_conn, trim($data->name)); $email = mysqli_real_escape_string($db_conn, trim($data->email)); $add = mysqli_query($db_conn,"insert into users (user_name,user_email) values('$name','$email')"); if($add){ $last_id = mysqli_insert_id($db_conn); echo json_encode(["success"=>true,"newids"=>$last_id]); return; }else{ echo json_encode(["success"=>false,"msg"=>"Server Problem. Please Try Again"]); return; } } else{ echo json_encode(["success"=>false,"msg"=>"Please fill all the required fields!"]); return; } ?>

GET – /client-all.php is for fetch all users.

client-all.php
<?php require 'db_connection.php'; $allUsers = mysqli_query($db_conn,"SELECT * FROM users order by id desc"); if(mysqli_num_rows($allUsers) > 0){ while($row_users = mysqli_fetch_array($allUsers)){ $json_array[] = array( 'id' => $row_users['id'], 'user_name' => $row_users['user_name'], 'user_email' => $row_users['user_email'], ); } echo json_encode(["success"=>true,"fetchusers"=>$json_array]); return; } else{ echo json_encode(["success"=>false]); return; } ?>

POST – /client-update.php is for updating an existing user

Required Fileds – id, user_name, user_email

client-update.php
<?php require 'db_connection.php'; $data = json_decode(file_get_contents("php://input")); if(isset($data->name) && isset($data->email) && !empty(trim($data->name)) && !empty(trim($data->email)) ){ $name = mysqli_real_escape_string($db_conn, trim($data->name)); $email = mysqli_real_escape_string($db_conn, trim($data->email)); $userid = mysqli_real_escape_string($db_conn, trim($data->userid)); $edit = mysqli_query($db_conn,"UPDATE users set user_name='".$name."',user_email='".$email."' where id= '".$userid."' "); if($edit){ echo json_encode(["success"=>true]); return; }else{ echo json_encode(["success"=>false,"msg"=>"Server Problem. Please Try Again"]); return; } } else{ echo json_encode(["success"=>false,"msg"=>"Please fill all the required fields!"]); return; } ?>

POST – /client-delete.php is obviously for deleting an existing user.

Required Fields – id

client-delete.php
<?php require 'db_connection.php'; $data = json_decode(file_get_contents("php://input")); $userid = mysqli_real_escape_string($db_conn, trim($data->userid)); $allUsers = mysqli_query($db_conn,"Delete FROM users where id=$userid "); if($userid){ echo json_encode(["success"=>true]); return; } else{ echo json_encode(["success"=>false]); return; } ?>

React Context API

React Context API is connect to mysqli database. It is easy to work.