Thursday, January 22, 2026

PHP React.js CRUD Application using Vite + React.js

 

Step 1:- Create a React Project 
  • Open your terminal or command prompt and run:
npx create-react-app phpreactcurd


Core packages install

Step 2:- Now run the server by using command 
  • Run the command to under the react app:
    D:\xampp\htdocs\weblession>cd phpreactcurd
  • Start the server:
    D:\xampp\htdocs\weblession\phpreactcurd>npm start


Step 3:-Now we want to use bootstrap library under these react application.
  • We have run this command for bootstrap library:
    => htdocs\weblession\phpreactcurd> npm install bootstrap

  • Now you can check inside the node_modules folder:

Step 4:- Now we want to import the Bootstrap library.
  • Now open the app.js file:

  • Start the server:
    D:\xampp\htdocs\weblession\phpreactcurd>npm start
    output














Step 5:- Now we will create a user list component for the table.
  • Create a component folder inside the src/ folder
  • Inside the component folder, create the Userlist.js file.

                                       User Table Display

Step 6:- Now we will import the Userlist.js component inside the app.js file.
  • We want to install the react-router-dom library.
     Press:- ctr + c (Stop Server)
    => htdocs\weblession\phpreactcurd> npm install react-router-dom

  • Now we want to import the Dom library

  • BrowserRouter:  It represents the router for your application, and it is a key component of React Router that provides routing functionality to react application.
  • Routes: The routes component is typically used to define a collection of routes.
  • Route: The route component is used to define an individual route in your application.
  • Link: Link component is used to creating hyperlink that navigates to different parts of your application.
    Note:- All components of this React Router DOM library.

Step 7: Now, import the Userlist component which we have created earlier so here we have to import the Userlist.js component into the app.js file and show the output.

Userlist.js

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import Userlist from './Component/Userlist';


function App() {
  return (
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Userlist />} />
          </Routes>
        </BrowserRouter>
  );
}

export default App;



Output:-

                         Fetch Data From Mysql


Now we want to import the two component useEffect and useState:
  • useEffect:-  This useEffect is a React hook that allows us to perform side effects in our component, and these side effects we can use for data fetching or for DOM manipulation
  • useState:-  useState hook is also a React hook which enables functional components to manage local statge we can use this use statement to create or update a state variable within a functional component.
Step 8: Now, create the MySQL table.


 
Step 8: Now, we want to add the backed fetch data api.
  •     Created a new directory with the name API, and under this directory, we have created a PHP file with the name action.php.
    action.php
<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE

if($method == 'GET')
{
$query = "SELECT * FROM sampleuser ORDER BY id DESC";
$result = mysqli_query($conn, $query);

$data = array();

foreach ($result as $key => $row) {
$data[] = $row;
}

echo json_encode($data);
}

?>

output:- 


Step 9:- Now show the user list in Userlist.js.

Userlist.js
import React, { useEffect, useState} from 'react';

function Userlist() {

const [users, setUsers] = useState([]);

useEffect(() => {
const apiUrl = "http://localhost/weblession/phpreactcurd/api/action.php";
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
setUsers(data);
});

}, []);

return (
<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6"><b>User Data</b></div>
<div className="col-md-6">
</div>
</div>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{ users.map((user, index) => 
<tr key = {index}>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
<td>{user.email}</td>
<td></td>
</tr>

)
}
</tbody>
</table>
</div>
</div>

)
}

export default Userlist;

output:- 

                     Insert Data in Mysql

Step 1:- Make Form & Set Route
Add.js

  • Import the add file and configure the route.
  • In Userlist.js, added one button with the name of add and set the route.
            import { Link } from 'react-router-dom';

            <Link to="/add" className="btn btn-success btn-sm float-end">Add</Link>
  • Now, we want to click on the Add button to open the submission form.

Step 2:- Make Insert Data Component & Summit Form Data

  • Now we want to import the useNavigate hook.


  • useNavigate:- This hook for use navigate from one route to another route.


Add.js

import React, {useState } from 'react';

import { Link, useNavigate } from 'react-router-dom';

function Add() {
let navigate = useNavigate();
//initialize  the properties
const [user, setUser] = useState({
first_name : '',
last_name : '',
email: ''
});

const handleChange = (event) => {
const { name, value } = event.target;

setUser({
...user,
[name] : value
});
};

const handleSubmit = (event) => {

event.preventDefault();

fetch("http://localhost/weblession/phpreactcurd/api/action.php", {
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(user)
})
.then((response) => response.json())
.then((data) => {
navigate("/");
})
}

//full explanation of logic click here

return (

<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6">Add User</div>
<div className="col-md-6">
<Link to="/" className="btn btn-success btn-sm float-end">View All</Link>
</div>
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-md-4">&nbsp;</div>
<div className="col-md-4">
<form method = "POST" onSubmit={handleSubmit}>
<div className="mb-3">
<label>First Name</label>
<input type="text" name="first_name" className="form-control" onChange={handleChange} />
</div>
<div className="mb-3">
<label>Last Name</label>
<input type="text" name="last_name" className="form-control" onChange={handleChange} />
</div>
<div className="mb-3">
<label>Email</label>
<input type="email" name="email" className="form-control" onChange={handleChange} />
</div>
<div className="mb-3">
<input type="submit" className="btn btn-primary" value="Add" />
</div>
</form>
</div>
</div>
</div>
</div>
);
}

export default Add;

Step 2:- Created a new directory with the name API, and under this directory, we have created a PHP file with the name action.php.



Action.php

<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE

if($method === 'POST')
{
$form_data = json_decode(file_get_contents('php://input'));

$first_name = $form_data->first_name ?? '';
$last_name  = $form_data->last_name ?? '';
$email      = $form_data->email ?? '';
$query = "INSERT INTO sampleuser (first_name, last_name, email)
          VALUES ('$first_name', '$last_name', '$email')";

    mysqli_query($conn, $query);

    echo json_encode(["status" => "success"]);

}


                    Update Data in Mysql

Step 1:- Make Form & Set Router for Edit Data Component


Make Route:
 

  • Make Route:- App.js

import Edit from './Component/Edit';

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';


function App() {

  return (

        <BrowserRouter>

          <Routes>

            <Route path="/edit/:user_id" element={<Edit />} />

          </Routes>

        </BrowserRouter>

  );

}


export default App;

  •  Edit Button:- Added the link in the Action column.

    Userlist.js

<td>

    <Link to={`/edit/${user.id}`} className="btn btn-warning btn-sm">Edit</Link>

</td>
  •  Target URL:- when click on link to call API.

    Edit.js 

    const apiUrl = 

    `http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`;


  • View All Button:- Added the link in the Action column.

    Edit.js

<div className="col-md-6">

<Link to="/" className="btn btn-success btn-sm float-end">View All</Link>

</div>


Make a form and fetch data


Edit.js

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

import { Link, useNavigate, useParams } from 'react-router-dom';

function Edit() {

const {user_id} = useParams(); // get id from URL

//console.log({user_id})

//hold data

const [user, setUser] = useState({

first_name : '',

last_name : '',

email : '',

});

const handleChange = (event) => {

const {name, value} = event.target;

setUser({

...user, // spread operator wit user variable

[name] : value

})

}

//fetch data from mysql database

const fetchUserData = () => {

fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`)

.then((response) => response.json())

.then((data) => {

//console.log(data);

setUser(data);

});

};

useEffect(() => {

fetchUserData();

},[]);

//console.log(user);

return(

<div className = "card">

<div className = "card-header">

<div className = "row">

<div className="col-md-6">Edit User</div>

<div className="col-md-6">

                    <Link to="/" className="btn btn-success btn-sm float-end">

                                                        View All</Link>

            </div>

</div>

</div>

<div className="card-body">

<div className="row">

<div className="col-md-4">&nbsp;</div>

<div className="col-md-4">

<form method = "POST">

<div className="mb-3">

<label>First Name</label>

<input type="text" 

                                                                                name="first_name" 

                                                                                className="form-control" 

                                                                                 value={user.first_name} 

                                                                                 onChange={handleChange} />

</div>

<div className="mb-3">

<label>Last Name</label>

<input type="text" name="last_name" className="form-control" value={user.last_name} onChange={handleChange} />

</div>

<div className="mb-3">

<label>Email</label>

<input type="email" name="email" className="form-control" value={user.email} onChange={handleChange} />

</div>

<div className="mb-3">

<input type="submit" className="btn btn-primary" value="Edit" />

</div>

</form>

</div>

</div>

</div>

</div>

);

}

export default Edit;

Step 2:- Created a new directory with the name API, and under this directory, we have created a PHP file with the name action.php.


Action.php.

<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE

if($method == 'GET')
{
if(isset($_GET['id']))
{
//fetch single user
$query = "SELECT * FROM sampleuser WHERE id = '".$_GET["id"]."'";

$result = mysqli_query($conn, $query);

$data = array();

foreach ($result as $key => $row) {
$data['first_name'] = $row['first_name'];
$data['last_name'] = $row['last_name'];
$data['email'] = $row['email'];

$data['id'] = $row['id'];
}

echo json_encode($data);
}
}
?>

                     Make Update Data API


Structure:- 



Edit.js.


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

import { Link, useNavigate, useParams } from 'react-router-dom';

function Edit() {

const {user_id} = useParams();

//console.log({user_id})

//hold data
const [user, setUser] = useState({
first_name : '',
last_name : '',
email : '',
});

const handleChange = (event) => {
const {name, value} = event.target;

setUser({
...user, // spread operator wit user variable
[name] : value
})
}

//fetch data from mysql database

const fetchUserData = () => {
fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`)
.then((response) => response.json())
.then((data) => {
//console.log(data);
setUser(data);
});
};

useEffect(() => {
fetchUserData();
},[]);

//console.log(user);
let navigate = useNavigate();

const handleSubmit = (event) => {

event.preventDefault();
//alert(user_id);

fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`, {
method : 'PUT',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(user)
})
.then((response) => response.json())
.then((data) => {
console.log(data);
navigate("/");
})
}


return(

<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6">Edit User</div>
<div className="col-md-6">
<Link to="/" className="btn btn-success btn-sm float-end">View All</Link>
</div>
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-md-4">&nbsp;</div>
<div className="col-md-4">
<form method="POST" onSubmit={handleSubmit}>
<div className="mb-3">
<label>First Name</label>
<input type="text" name="first_name" className="form-control" value={user.first_name} onChange={handleChange} />
</div>
<div className="mb-3">
<label>Last Name</label>
<input type="text" name="last_name" className="form-control" value={user.last_name} onChange={handleChange} />
</div>
<div className="mb-3">
<label>Email</label>
<input type="email" name="email" className="form-control" value={user.email} onChange={handleChange} />
</div>
<div className="mb-3">
<input type="submit" className="btn btn-primary" value="Edit" />
</div>
</form>
</div>
</div>
</div>
</div>
);
}

export default Edit;

Step 2:- Created a new directory with the name API, and under this directory, we have created a PHP file with the name action.php.


Action.php.


<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

header("Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PUT,POST,PATCH'");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE

if($method === 'PUT')
{
$form_data = json_decode(file_get_contents('php://input'));

$first_name = $form_data->first_name ?? '';
$last_name  = $form_data->last_name ?? '';
$email      = $form_data->email ?? '';
$id         = $form_data->id ?? 0;


// print_r($first_name);

$query = "UPDATE sampleuser 
          SET first_name = '$first_name',
              last_name = '$last_name',
              email = '$email'
          WHERE id = $id";
mysqli_query($conn, $query);

    echo json_encode(["status" => "update successfull"]);
    
}
?>

                 Create Delete Data API

  •  Delete Button:- We want to add the Delete button.
Userlist.js

  • Create button:- 

<button type="button" onClick={() => handleDelete(user.id)} className="btn btn-danger btn-sm">Delete</button>

  •  Call button:- 
const handleDelete = (user_id) => {
if(window.confirm("Are you sure to want to remove it?")) 
{
  console.log(user_id);
}
}

Now, we want to delete the row without refreshing the page.


Userlist.js

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

import { Link } from 'react-router-dom';

function Userlist() {

//Delete Data

const handleDelete = (user_id) => {
if(window.confirm("Are you sure to want to remove it?")) 
{
//console.log(user_id);
fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`, 
{
method : 'POST',
body: JSON.stringify({
    action: "delete",   // dummy flag
    id: {user_id},
  })
})
.then((response) => response.json())
.then((data) => {
setUsers((prevUser) => prevUser.filter((user) => user.id !== user_id));
});
}
}

return (
{ users.map((user, index) => 
<tr key = {index}>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
<td>{user.email}</td>
<td>
<Link to={`/edit/${user.id}`} className="btn btn-warning btn-sm">Edit</Link>&nbsp;

<button type="button" onClick={() => handleDelete(user.id)} className="btn btn-danger btn-sm">Delete</button>
</td>
</tr>

)
}
);
}
export default Userlist;

Action.php

<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

header("Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PUT,POST,PATCH'");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE


if($method === 'POST')
{
$form_data = json_decode(file_get_contents("php://input"), true);

$action = $form_data['action'] ?? '';

if($action === 'delete') {
$id = $_GET['id'];

$query = "DELETE FROM sampleuser WHERE id = $id";
mysqli_query($conn, $query);

    echo json_encode(["status" => "Delete Done"]);
}
}
?>

                        Full Code of Data API



 src/ App.js

import 'bootstrap/dist/css/bootstrap.min.css';

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

import Userlist from './Component/Userlist';

import Add from './Component/Add';

import Edit from './Component/Edit';


function App() {
  return (
      <div className="container">
        <h1 className="mt-5 mb-5 text-center"><b>PHP React.js CRUD Application</b></h1>
        <BrowserRouter>
          <Routes>
                <Route path="/" element={<Userlist />} />
                <Route path="/add" element={<Add />} />
                <Route path="/edit/:user_id" element={<Edit />} />
          </Routes>
        </BrowserRouter>
      </div>
  );
}

export default App;

src/ Component/Userlist.js 


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

import { Link } from 'react-router-dom';

function Userlist() {

const [users, setUsers] = useState([]);

useEffect(() => {

const apiUrl = "http://localhost/weblession/phpreactcurd/api/action.php";

fetch(apiUrl)

.then((response) => response.json())

.then((data) => {
setUsers(data);
});

}, []);

//Delete Data

const handleDelete = (user_id) => {
if(window.confirm("Are you sure to want to remove it?")) 
{
//console.log(user_id);
fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`, 
{
method : 'POST',
body: JSON.stringify({
    action: "delete",   // dummy flag
    id: {user_id},
  })
})
.then((response) => response.json())

.then((data) => {
setUsers((prevUser) => prevUser.filter((user) => user.id !== user_id));
});
}
}

return (
<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6"><b>User Data</b></div>
<div className="col-md-6">
<Link to="/add" className="btn btn-success btn-sm float-end">Add</Link>
</div>
</div>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{ users.map((user, index) => 
<tr key = {index}>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
<td>{user.email}</td>
<td>
<Link to={`/edit/${user.id}`} className="btn btn-warning btn-sm">Edit</Link>&nbsp;
<button type="button" onClick={() => handleDelete(user.id)} className="btn btn-danger btn-sm">Delete</button>
</td>
</tr>

)
}
</tbody>
</table>
</div>
</div>

)
}

export default Userlist;

 

src/ Component/Add.js


import React, {useState } from 'react';

import { Link, useNavigate } from 'react-router-dom';

function Add() {

let navigate = useNavigate();

//initialize  the properties

const [user, setUser] = useState({
first_name : '',
last_name : '',
email: ''
});

const handleChange = (event) => {
const { name, value } = event.target;

setUser({
...user,
[name] : value
});
};

const handleSubmit = (event) => {

event.preventDefault();

fetch("http://localhost/weblession/phpreactcurd/api/action.php", {
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(user)
})
.then((response) => response.json())
.then((data) => {
navigate("/");
})
}

return (

<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6">Add User</div>
<div className="col-md-6">
<Link to="/" className="btn btn-success btn-sm float-end">View All</Link>
</div>
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-md-4">&nbsp;</div>
<div className="col-md-4">
<form method = "POST" onSubmit={handleSubmit}>

<div className="mb-3">
<label>First Name</label>
    <input type="text" 
                                                                name="first_name" 
                                                                className="form-control"
                                                                 onChange={handleChange} />
</div>
<div className="mb-3">
<label>Last Name</label>
<input type="text" name="last_name" className="form-control" onChange={handleChange} />
</div>
<div className="mb-3">
<label>Email</label>
<input type="email" name="email" className="form-control" onChange={handleChange} />
</div>
<div className="mb-3">
<input type="submit" className="btn btn-primary" value="Add" />
</div>
</form>
</div>
</div>
</div>
</div>
);
}

export default Add;

src/ Component/Edit.js


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

import { Link, useNavigate, useParams } from 'react-router-dom';

function Edit() {

const {user_id} = useParams();

//console.log({user_id})

//hold data
const [user, setUser] = useState({
first_name : '',
last_name : '',
email : '',
});

const handleChange = (event) => {
const {name, value} = event.target;

setUser({
...user, // spread operator wit user variable
[name] : value
})
}

//fetch data from mysql database

const fetchUserData = () => {
fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`)
.then((response) => response.json())
.then((data) => {
//console.log(data);
setUser(data);
});
};

useEffect(() => {
fetchUserData();
},[]);

//console.log(user);
let navigate = useNavigate();

const handleSubmit = (event) => {

event.preventDefault();
//alert(user_id);

fetch(`http://localhost/weblession/phpreactcurd/api/action.php?id=${user_id}`, {
method : 'PUT',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(user)
})
.then((response) => response.json())
.then((data) => {
console.log(data);
navigate("/");
})
}


return(

<div className = "card">
<div className = "card-header">
<div className = "row">
<div className="col-md-6">Edit User</div>
<div className="col-md-6">
<Link to="/" className="btn btn-success btn-sm float-end">View All</Link>
</div>
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-md-4">&nbsp;</div>
<div className="col-md-4">

<form method="POST" onSubmit={handleSubmit}>
<div className="mb-3">
<label>First Name</label>
<input type="text" name="first_name" className="form-control" value={user.first_name} onChange={handleChange} />
</div>
<div className="mb-3">
<label>Last Name</label>
<input type="text" name="last_name" className="form-control" value={user.last_name} onChange={handleChange} />
</div>
<div className="mb-3">
<label>Email</label>
<input type="email" name="email" className="form-control" value={user.email} onChange={handleChange} />
</div>
<div className="mb-3">
<input type="submit" className="btn btn-primary" value="Edit" />
</div>
</form>

</div>
</div>
</div>
</div>
);
}

export default Edit;

api/ action.php


<?php

header("Access-Control-Allow-Origin:* ");

header("Access-Control-Allow-Headers:* ");

header("Access-Control-Allow-Method:* ");

header("Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PUT,POST,PATCH'");

$conn = mysqli_connect('localhost','root','','reactuser', 3307);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$method = $_SERVER['REQUEST_METHOD']; // return GET, POST, PUT, DELETE

if($method == 'GET')
{
if(isset($_GET['id']))
{
//fetch single user
$query = "SELECT * FROM sampleuser WHERE id = '".$_GET["id"]."'";

$result = mysqli_query($conn, $query);

$data = array();

foreach ($result as $key => $row) {
$data['first_name'] = $row['first_name'];
$data['last_name'] = $row['last_name'];
$data['email'] = $row['email'];

$data['id'] = $row['id'];
}

echo json_encode($data);

}
else{

//fetch all user

$query = "SELECT * FROM sampleuser ORDER BY id DESC";
$result = mysqli_query($conn, $query);

$data = array();

foreach ($result as $key => $row) {
$data[] = $row;
}

echo json_encode($data);
}
}

if($method === 'POST')
{
$form_data = json_decode(file_get_contents("php://input"), true);

$action = $form_data['action'] ?? '';
if($action === 'delete') {
$id = $_GET['id'];

$query = "DELETE FROM sampleuser WHERE id = $id";
mysqli_query($conn, $query);

    echo json_encode(["status" => "Delete Done"]);
}
else {
// $form_data = json_decode(file_get_contents('php://input'));

$first_name = $form_data->first_name ?? '';
$last_name  = $form_data->last_name ?? '';
$email      = $form_data->email ?? '';
$query = "INSERT INTO sampleuser (first_name, last_name, email)
          VALUES ('$first_name', '$last_name', '$email')";

    mysqli_query($conn, $query);

    echo json_encode(["status" => "success"]);
}
}

if($method === 'PUT')
{
$form_data = json_decode(file_get_contents('php://input'));

$first_name = $form_data->first_name ?? '';
$last_name  = $form_data->last_name ?? '';
$email      = $form_data->email ?? '';
$id         = $form_data->id ?? 0;

// print_r($first_name);

$query = "UPDATE sampleuser 
          SET first_name = '$first_name',
              last_name = '$last_name',
              email = '$email'
          WHERE id = $id";
mysqli_query($conn, $query);

    echo json_encode(["status" => "update successfull"]);
    
}

?>

No comments:

Post a Comment

If you have any problem please let me know.