PHP REST API CRUD – Step 5

PHP REST API CRUD – Step 5

Step 5 Create API for user

  • Create user folder and Create a new file called create_user.php 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 create () 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);

// set user property values
$user->name = $data->name;
$user->email = $data->email;
$user->password = $data->password;

// create the user
if (
    !empty($user->name) &&
    !empty($user->email) &&
    !empty($user->password) &&
    $user->create()
) {

    // set response code
    http_response_code(200);
    // display message: user was created
    echo json_encode(array("message" => "User was created."));
}

// message if unable to create user
else {

    // set response code
    http_response_code(400);
    // display message: unable to create user
    echo json_encode(array("message" => "Unable to create user."));
}

Post Your Comments & Reviews

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

*

*