The Axios PUT method is used to update an existing resource through a REST API. In a React Native application, Axios can send updated data to a PHP REST API, which can then update the corresponding record in MySQL.
A PUT request is commonly used to update an existing resource.
React Native
↓
Axios PUT
↓
PHP REST API
↓
Validate
↓
MySQL
↓
Updated Record
↓
JSON Response
| POST | PUT |
|---|---|
| Usually creates a resource | Usually updates an existing resource |
| Example: Add student | Example: Update student |
| Usually does not require an existing ID | Usually identifies an existing resource |
const response =
await axios.put(
API_URL,
data
);
The first argument is the API URL and the second argument contains the updated data.
const response =
await axios.put(
`${API_URL}?id=10`,
{
name: "Rahul Kumar",
email: "rahul@example.com",
course: "React Native"
}
);
console.log(
response.data
);
Here, id=10 identifies the student that should be updated.
async function updateStudent() {
try {
const response =
await axios.put(
`${API_URL}?id=10`,
{
name: "Rahul Kumar",
course: "React Native"
}
);
console.log(
response.data
);
} catch (error) {
console.log(
error.message
);
}
}
The request body contains the data that should be updated.
{
"name": "Rahul Kumar",
"email": "rahul@example.com",
"course": "TypeScript"
}
Axios can send this JavaScript object as JSON.
const response =
await axios.put(
`${API_URL}?id=10`,
{
name: "Rahul Kumar",
course: "TypeScript"
},
{
headers: {
"Content-Type":
"application/json"
}
}
);
PHP can read the JSON body of a PUT request using php://input.
$input = json_decode(
file_get_contents(
"php://input"
),
true
);
The API needs to know which student should be updated.
$id = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
The API should validate the ID before executing the update.
if (!$id) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Valid student ID is required"
]);
exit;
}
$name =
trim($input['name'] ?? '');
$email =
trim($input['email'] ?? '');
$course =
trim($input['course'] ?? '');
These values should be validated before updating the database.
if (
$name === '' ||
$email === '' ||
$course === ''
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"All fields are required"
]);
exit;
}
$check = $pdo->prepare(
"SELECT id
FROM students
WHERE id = ?"
);
$check->execute([
$id
]);
if (!$check->fetch()) {
http_response_code(404);
echo json_encode([
"success" => false,
"message" =>
"Student not found"
]);
exit;
}
Use a prepared UPDATE statement to modify the existing record.
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$course,
$id
]);
Remember that rowCount() can be 0 when the submitted values are identical to the existing values. Therefore, it should not automatically be treated as "student not found" when you have already checked that the record exists.
$getStudent = $pdo->prepare(
"SELECT id, name, email, course
FROM students
WHERE id = ?"
);
$getStudent->execute([
$id
]);
$student =
$getStudent->fetch(
PDO::FETCH_ASSOC
);
http_response_code(200);
echo json_encode([
"success" => true,
"message" =>
"Student updated successfully",
"data" => $student
]);
React Native can read the JSON response using response.data.
const response =
await axios.put(
`${API_URL}?id=${id}`,
student
);
console.log(
response.data.message
);
console.log(
response.data.data
);
const [name, setName] =
useState("");
const [email, setEmail] =
useState("");
const [course, setCourse] =
useState("");
const [loading, setLoading] =
useState(false);
const [message, setMessage] =
useState("");
async function updateStudent() {
setLoading(true);
setMessage("");
try {
const response =
await axios.put(
`${API_URL}?id=${studentId}`,
{
name: name.trim(),
email: email.trim(),
course: course.trim()
}
);
setMessage(
response.data.message
);
} catch (error) {
setMessage(
error.response?.data?.message ||
"Unable to update student"
);
} finally {
setLoading(false);
}
}
A protected update endpoint should verify the user's JWT token and authorization before changing the record.
const response =
await axios.put(
`${API_URL}?id=${studentId}`,
{
name,
email,
course
},
{
headers: {
Authorization:
`Bearer ${token}`
}
}
);
If the requested student does not exist, the PHP API can return HTTP 404 Not Found.
try {
await axios.put(
`${API_URL}?id=999`,
student
);
} catch (error) {
if (
error.response?.status === 404
) {
console.log(
"Student not found"
);
}
}
The server can return HTTP 422 when the submitted data is invalid.
catch (error) {
if (
error.response?.status === 422
) {
setMessage(
error.response.data.message
);
}
}
<Button
title="Update Student"
onPress={updateStudent}
/>
The button can call the update function when the user wants to save changes.
<TextInput
value={name}
onChangeText={setName}
placeholder="Student Name"
/>
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Email"
/>
<TextInput
value={course}
onChangeText={setCourse}
placeholder="Course"
/>
<Button
title="Update Student"
onPress={updateStudent}
/>
<Text>
{message}
</Text>
<?php
header(
"Content-Type: application/json"
);
require_once "../db.php";
$id = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
if (!$id) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Valid student ID is required"
]);
exit;
}
$input = json_decode(
file_get_contents(
"php://input"
),
true
);
if (!is_array($input)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Invalid JSON data"
]);
exit;
}
$name =
trim($input['name'] ?? '');
$email =
trim($input['email'] ?? '');
$course =
trim($input['course'] ?? '');
if (
$name === '' ||
$email === '' ||
$course === ''
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"All fields are required"
]);
exit;
}
if (
!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid email address"
]);
exit;
}
$check = $pdo->prepare(
"SELECT id
FROM students
WHERE id = ?"
);
$check->execute([
$id
]);
if (!$check->fetch()) {
http_response_code(404);
echo json_encode([
"success" => false,
"message" =>
"Student not found"
]);
exit;
}
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$course,
$id
]);
$getStudent = $pdo->prepare(
"SELECT id, name, email, course
FROM students
WHERE id = ?"
);
$getStudent->execute([
$id
]);
$student =
$getStudent->fetch(
PDO::FETCH_ASSOC
);
http_response_code(200);
echo json_encode([
"success" => true,
"message" =>
"Student updated successfully",
"data" => $student
]);
async function updateStudent() {
if (
name.trim() === "" ||
email.trim() === "" ||
course.trim() === ""
) {
setMessage(
"Please fill all fields"
);
return;
}
setLoading(true);
setMessage("");
try {
const response =
await axios.put(
`${API_URL}?id=${studentId}`,
{
name:
name.trim(),
email:
email.trim(),
course:
course.trim()
}
);
if (
response.status === 200
) {
setMessage(
response.data.message
);
}
} catch (error) {
if (error.response) {
setMessage(
error.response.data?.message ||
"Server error"
);
} else {
setMessage(
"Network error"
);
}
} finally {
setLoading(false);
}
}
After updating a student, the application may refresh the student list or update the corresponding item in local state.
await updateStudent();
const response =
await axios.get(
"/students.php"
);
setStudents(
response.data.data || []
);
Another approach is to update only the changed item in the existing state.
import React, {
useState
} from "react";
import {
View,
Text,
TextInput,
Button,
ActivityIndicator
} from "react-native";
import axios from "axios";
const API_URL =
"https://example.com/api/students.php";
export default function EditStudent({
studentId
}) {
const [name, setName] =
useState("");
const [email, setEmail] =
useState("");
const [course, setCourse] =
useState("");
const [loading, setLoading] =
useState(false);
const [message, setMessage] =
useState("");
async function updateStudent() {
if (
name.trim() === "" ||
email.trim() === "" ||
course.trim() === ""
) {
setMessage(
"Please fill all fields"
);
return;
}
setLoading(true);
setMessage("");
try {
const response =
await axios.put(
`${API_URL}?id=${studentId}`,
{
name:
name.trim(),
email:
email.trim(),
course:
course.trim()
}
);
setMessage(
response.data.message
);
} catch (error) {
if (error.response) {
setMessage(
error.response.data?.message ||
"Unable to update student"
);
} else {
setMessage(
"Network error"
);
}
} finally {
setLoading(false);
}
}
return (
<View style={{
padding: 20
}}>
<Text>
Edit Student
</Text>
<TextInput
value={name}
onChangeText={setName}
placeholder="Student Name"
/>
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Email"
keyboardType=
"email-address"
/>
<TextInput
value={course}
onChangeText={setCourse}
placeholder="Course"
/>
{loading && (
<ActivityIndicator
size="small"
/>
)}
<Button
title="Update Student"
onPress={updateStudent}
/>
<Text>
{message}
</Text>
</View>
);
}
React Native Edit Form
↓
User Input
↓
axios.put()
↓
JSON Request
↓
PHP REST API
↓
Validate
↓
Check Student ID
↓
Prepared SQL
↓
MySQL
↓
Update Record
↓
JSON Response
↓
React Native
↓
Update UI / List
Axios PUT requests are useful for editing existing records such as students, users, products, profiles and other resources.
Question: Which Axios method is commonly used to update an existing resource?