Read Data with REST API in PHP

 <?php


$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

//Create Connection
$conn = new mysqli($servername, $username, $password, $database);

//Check Connection
if ($conn->connect_error) {
    die("Connection Failed: " . $conn->connect_error);
}
Above File is mysqli_conn.php File which is included in below Files.






Below is api-fetch-all.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

include("mysqli_conn.php");

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
    $output = $result->fetch_all(MYSQLI_ASSOC); //Fetch all rows and return the result-set as an associative array
    echo json_encode($output);
} else {
    echo json_encode(array(
        "message" => "No Record Found.",
        "status" => false
    ));
}







Below is api-fetch-single.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

$data = json_decode(file_get_contents("php://input"), true);

$student_id = $data["sid"];

include("mysqli_conn.php");

$sql = "SELECT * FROM students WHERE id = {$student_id}";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
    $output = $result->fetch_all(MYSQLI_ASSOC); //Fetch all rows and return the result-set as an associative array
    echo json_encode($output);
} else {
    echo json_encode(array(
        "message" => "No Record Found.",
        "status" => false
    ));
}





Comments

Popular posts from this blog

Logical_Operators

SubQuery with EXISTS and NOT EXISTS in PHP

Get Functions