API - GET, POST, DELETE - REACT JS, CORE PHP
API - GET, POST, DELETE - REACT JS, CORE PHP
ROUTE NPM INSTALL LINK AND AXIOS LINK
IN REACT, SRC, FOLDER IN COMPONENTS :
MAKE FILE: CreateUser.js
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
export default function CreateUser(){
const navigate = useNavigate();
const [inputs, setInputs ] = useState({})
const handleChange = (event) =>{
const name = event.target.name ;
const value = event.target.value ;
setInputs(values => ({...values, [name]:value}));
}
const handleSubmit = (event) =>{
event.preventDefault();
axios.post('http://localhost/api/user/save', inputs).then(function (response){
console.log(response.data);
navigate('/');
});
}
return (
<div>
<h1>Create User</h1>
<form onSubmit={handleSubmit}>
<table cellSpacing="10">
<tbody>
<tr>
<th>
<label>Name: </label>
</th>
<td><input type="text" name="name" onChange={handleChange}/></td>
</tr>
<tr>
<th>
<label>Email: </label>
</th>
<td><input type="email" name="email" onChange={handleChange}/></td>
</tr>
<tr>
<th>
<label>Mobile: </label>
</th>
<td><input type="text" name="mobile" onChange={handleChange}/></td>
</tr>
<tr>
<td colSpan="2" align="right">
<button type="">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
)
}
EditUser.js
import { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";
export default function EditUser(){
const navigate = useNavigate();
const [inputs, setInputs ] = useState([]);
const {id} = useParams();
useEffect(() =>{
getUser();
}, []);
function getUser(){
axios.get(`http://localhost/api/user/${id}`).then(function(response){
console.log(response.data);
setInputs(response.data);
});
}
const handleChange = (event) =>{
const name = event.target.name ;
const value = event.target.value ;
setInputs(values => ({...values, [name]:value}));
}
const handleSubmit = (event) =>{
event.preventDefault();
axios.put(`http://localhost/api/user/${id}/edit`, inputs).then(function (response){
console.log(response.data);
navigate('/');
});
}
return (
<div>
<h1>Edit User</h1>
<form onSubmit={handleSubmit}>
<table cellSpacing="10">
<tbody>
<tr>
<th>
<label>Name: </label>
</th>
<td><input value={inputs.name} type="text" name="name" onChange={handleChange}/></td>
</tr>
<tr>
<th>
<label>Email: </label>
</th>
<td><input value={inputs.email} type="email" name="email" onChange={handleChange}/></td>
</tr>
<tr>
<th>
<label>Mobile: </label>
</th>
<td><input value={inputs.mobile} type="text" name="mobile" onChange={handleChange}/></td>
</tr>
<tr>
<td colSpan="2" align="right">
<button>Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
)
}
ListUser.js
import axios from "axios";
import { useEffect, useState } from "react";
import {Link} from 'react-router-dom';
export default function ListUser(){
const [users, setUsers] = useState([]);
useEffect(() =>{
getUsers();
}, []);
function getUsers(){
axios.get('http://localhost/api/users').then(function(response){
console.log(response.data);
setUsers(response.data);
});
}
const deleteUser = (id)=>{
axios.delete(`http://localhost/api/user/${id}/delete`).then(function(response){
console.log(response.data);
getUsers();
});
}
return (
<div>
<h1>List Users</h1>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{users.map((user,key)=>
<tr key ={key}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.mobile}</td>
<td>
<Link to={`user/${user.id}/edit`} style={{marginRight:"10px"}}>Edit</Link>
<button onClick={()=> deleteUser(user.id)}>DELETE</button>
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
Inside Src Folder,
App.js
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import './App.css';
import ListUser from './components/ListUser';
import CreateUser from './components/CreateUser';
import EditUser from './components/EditUser';
function App() {
return (
<div className="App">
<h5>React Crud Operations using PHP API and MySQL</h5>
<BrowserRouter>
<nav>
<ul>
<li>
<Link to="/">List Users</Link>
</li>
<li>
<Link to="/user/create">Create User</Link>
</li>
</ul>
</nav>
<Routes>
<Route index element={<ListUser />} />
<Route path="user/create" element={<CreateUser />} />
<Route path="user/:id/edit" element={<EditUser />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
Some install packages ,
npm install axios
npm install react-router-dom
Now in PHP, API related functions
create an api folder in htdocs , under this folder,
create .htaccess
RewriteEngine On
#handle front controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Inside, DbConnect.php
<?php
/**
* Database Connection
*/
class DbConnect {
private $server = 'localhost';
private $dbname = 'react-crud';
private $user = 'root';
private $pass = '';
public function connect() {
try {
$conn = new PDO('mysql:host=' .$this->server .';dbname=' . $this->dbname, $this->user, $this->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (\Exception $e) {
echo "Database Error: " . $e->getMessage();
}
}
}
?>
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");
include 'DbConnect.php';
$objDb = new DbConnect;
$conn = $objDb->connect();
// var_dump($conn);
// $user = file_get_contents('php://input');
$method = $_SERVER['REQUEST_METHOD'];
switch($method){
case "POST":
$user = json_decode(file_get_contents('php://input') );
$sql = "INSERT INTO users(id, name, email, mobile, created_at) values (null, :name, :email, :mobile, :created_at)";
$stmt = $conn->prepare($sql);
$created_at =date('Y-m-d');
$stmt->bindParam(":name",$user->name);
$stmt->bindParam(":email",$user->email);
$stmt->bindParam(":mobile",$user->mobile);
$stmt->bindParam(":created_at",$created_at);
if($stmt->execute())
{
$response = ['status'=> 1, 'message'=> 'Record Created Successfully'];
}else{
$response = ['status'=> 0, 'message'=> 'Failed to Create Record.'];
}
echo json_encode($response);
break;
case "GET":
$sql = "SELECT * FROM users";
$path = explode('/', $_SERVER['REQUEST_URI']);
if(isset($path[3]) && is_numeric($path[3])){
$sql.=" Where id=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id",$path[3]);
$stmt->execute();
$users = $stmt->fetch(PDO::FETCH_ASSOC);
}else{
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($users);
break;
case "PUT":
$user = json_decode(file_get_contents('php://input') );
$sql = "UPDATE users SET name= :name, email= :email, mobile= :mobile, updated_at= :updated_at Where id= :id";
$stmt = $conn->prepare($sql);
$updated_at =date('Y-m-d');
$stmt->bindParam(":id",$user->id);
$stmt->bindParam(":name",$user->name);
$stmt->bindParam(":email",$user->email);
$stmt->bindParam(":mobile",$user->mobile);
$stmt->bindParam(":updated_at",$updated_at);
if($stmt->execute())
{
$response = ['status'=> 1, 'message'=> 'Record Updated Successfully'];
}else{
$response = ['status'=> 0, 'message'=> 'Failed to Update Record.'];
}
echo json_encode($response);
break;
case "DELETE":
$sql = "DELETE FROM users where id = :id";
$path = explode('/', $_SERVER['REQUEST_URI']);
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id",$path[3]);
if($stmt->execute())
{
$response = ['status'=> 1, 'message'=> 'Record Deleted Successfully'];
}else{
$response = ['status'=> 0, 'message'=> 'Failed to Delete Record.'];
}
echo json_encode($response);
break;
}
?>
In xampp, create a db. ex: react-crud
Comments
Post a Comment