PHP REST API - Fetch Data from SQL Database

 api-fetch-all.php:


<?php
header('Content-Type: application/json');
header('Acess-Control-Allow-Origin: *');
include "config.php";

$sql="SELECT * FROM students";

$result=mysqli_query($conn, $sql) or die("SQL query failed");

if(mysqli_num_rows($result)>0){
    $output=mysqli_fetch_all($result, MYSQLI_ASSOC);
    echo json_encode($output);

}else{
    echo json_encode(array('message'=>'NO RECORD FOUND', 'status'=>false));

}

?>


-------------------------

api-fetch-single.php:


<?php
header('Content-Type: application/json');
header('Acess-Control-Allow-Origin: *');

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

$student_id=$data['sid'];

include "config.php";

$sql="SELECT * FROM students WHERE id={$student_id}";

$result=mysqli_query($conn, $sql) or die("SQL query failed");

if(mysqli_num_rows($result)>0){
    $output=mysqli_fetch_all($result, MYSQLI_ASSOC);
    echo json_encode($output);

}else{
    echo json_encode(array('message'=>'NO RECORD FOUND', 'status'=>false));

}

?>

------------------------

config.php:


<?php
$conn=mysqli_connect("localhost","root","","poetrydb") or die("Connection failed");



?>


Comments

Popular posts from this blog

Send Data Child to Parent Component - React Js

Hide , Show and Toggle in ReactJs

Importance Of Web Content In SEO.