Wednesday, 23 August 2023

API IN PHP

 <?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Max-Age: 3600");
include "conn.php";
$json = file_get_contents("php://input");
$obj= json_decode($json,true);
$method=$_SERVER['REQUEST_METHOD'];
$path=explode('/',$_SERVER['REQUEST_URI']);
switch ($method) {
    case 'GET' :
        if(isset($path[4]) && is_numeric($path[4]))
        {
            $result=mysqli_query($conn,"Select * from expence where ID='$path[4]'");
            if (mysqli_num_rows($result) > 0) {
                while($row = mysqli_fetch_assoc($result)) {
                  $data=json_encode($row);
                }
                echo $data;
            }
            else
            {
                echo json_encode("result not found.");
            }
        }
        else
        {
            $result=mysqli_query($conn,"Select * from expence");
        if (mysqli_num_rows($result) > 0) {
            while($row[] = mysqli_fetch_assoc($result)) {
              $data=json_encode($row);
            }
            echo $data;
        }
        else
        {
            echo json_encode("result not found.");
        }
        }
        break;
    case 'POST':
        $dE=$obj["DE"];
        $aMOUNT=$obj["AMOUNT"];
        $tYPE=$obj["TYPE"];
        $yEAR=$obj["YEAR"];
        $cDATE=$obj["CDATE"];
        $result=mysqli_query($conn,"INSERT INTO `expence`(`DE`, `AMOUNT`, `TYPE`, `YEAR`, `CDATE`) VALUES ('$dE','$aMOUNT','$tYPE','$yEAR','$cDATE')");
        if($result)
        {
            echo json_encode("Data Inserted successfully.");
        }
        else
        {
            echo json_encode("Something went wrong.");
        }
        break;
        case 'PUT':
            $iD=$obj["ID"];
            $dE=$obj["DE"];
            $aMOUNT=$obj["AMOUNT"];
            $tYPE=$obj["TYPE"];
            $yEAR=$obj["YEAR"];
            $cDATE=$obj["CDATE"];
            $result=mysqli_query($conn,"UPDATE `expence` SET `DE`='$dE',`AMOUNT`='$aMOUNT',`TYPE`='$tYPE',`YEAR`='$yEAR',`CDATE`='$cDATE'  WHERE ID='$iD'");
            if($result)
            {
                echo json_encode("Data Updated successfully.");
            }
            else
            {
                echo json_encode("Something went wrong.");
            }  
            break;
            case 'DELETE':
                $iD=$obj["ID"];
    $result=mysqli_query($conn,"delete from  expence where ID='$iD'");
    if($result)
    {
        echo json_encode("Data deleted successfully.");
    }
    else
    {
        echo json_encode("Something went wrong.");
    }
                break;
    default:

        echo 'Something went wrong.';

        break;

}
mysqli_close($conn);
?>

No comments:

Post a Comment