PHP REST API CRUD – Step 10
Step 10 Create API for update data
- Create a new file called update_user.php in user folder and Following steps to be performed for this
- We need to set headers on this new file.
2. Connect to database and register table
3. Assign submitted data to object properties
4. Use the update method
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// files needed to connect to database
include '../config/database.php';
include '../objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// instantiate user object
$user = new User($db);
// get posted data
$json = json_encode($_POST);
$data = json_decode($json);
echo json_encode(array("data" => $data, "id" => $_GET["id"]));
// make sure data is not empty
if (
!empty($data->name) &&
!empty($data->email) &&
!empty($data->password)
) {
// set data property values
$user->name = $data->name;
$user->email = $data->email;
$user->password = $data->password;
// update the data
if ($user->update($_GET["id"])) {
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "user data is updated."));
}
// if unable to create the data, tell the user
else {
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to update data."));
}
}
// tell the user data is incomplete
else {
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to update data. Data is incomplete."));
}