PHP REST API CRUD – Step 12

PHP REST API CRUD – Step 12

Step 12 Create API for delete data

  • Create a new file called delete_user.php in user folder and Following steps to be performed for this
  1. 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 delete 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);

// delete user from the db
if (isset($_GET['id'])) {
    $stmt = $user->delete($_GET["id"]);

    // set response code - 201 created
    http_response_code(201);

    // tell the user
    echo json_encode(array("message" => "user is deleted."));
}

// if unable to delete the quiz, tell the user
else {

    // set response code - 503 service unavailable
    http_response_code(503);

    // tell the user
    echo json_encode(array("message" => "Unable to delete user."));
}

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*