PHP REST API CRUD – Step 8

PHP REST API CRUD – Step 8

Step 8 Create API for read single and all data

  • Create a new file called read_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 read () and readSingleUser() 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);

if (isset($_GET["id"])) {
    $stmt = $user->readSingleUser($_GET["id"]);
    if ($stmt) {
        $row = $stmt->fetchAll();
        http_response_code(200);
        echo json_encode(array("message" => "Login Successfully.", "data" => $row));
    } else {
        http_response_code(401);
        echo json_encode(array("message" => "Invalid Credential."));
    }
} else {
    $stmt = $user->read();
    $rowcount = $stmt->rowCount();
    if ($rowcount > 0) {
        // set response code - 200 found
        $data = array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            extract($row);
            array_push($data, array(
                "id" => $row["id"],
                "name" => $row["name"],
                "email" => $row["email"],
                "password" => $row["password"],
            ));
        }
        http_response_code(200);
        echo json_encode(array("message" => "Read data Successfully.", "data" => $data));

    } else {
        http_response_code(401);
        echo json_encode(array("message" => "issue in Read data Request."));
    }
}

To read all and single user data, open POSTMAN. Enter the following as the request URL

http://localhost/PHP REST API CRUD with JWT Authentication\api\ User\

read_user.php

http://localhost/PHP REST API CRUD with JWT Authentication\api \User\ read_user.php? Id=3

Post Your Comments & Reviews

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

*

*