i'm trying a simple Rest api the GET and POST methods works but then when i try to test the PUT and DELETE Undefined Index
errors show and ofc the database doesn't get updated, i tried inputing the data through form-data
and raw
ass well as x-www-form-urlencoded
but yeah nothing
when I input manually the data into my code instead of $_REQUEST
it works just fine
here's my code :
<?php
try{
include 'connection.php';
$method_name=$_SERVER["REQUEST_METHOD"];
if($_SERVER["REQUEST_METHOD"])
{
switch ($method_name)
{
case 'GET':
$qry="SELECT * from product";
$result=mysqli_query($conn, $qry);
while ($row=mysqli_fetch_row($result))
{
$temp_cat[]=array("product_id"=>$row[0],"product_name"=>$row[1],"product_price"=>$row[2],"product_qty"=>$row[3]);
}
$data=array("status"=>"1","message"=>"success","result"=>$temp_cat);
break;
case 'POST':
$name=$_REQUEST['product_name'];
$price=$_REQUEST['product_price'];
$qty=$_REQUEST['product_qty'];
$qry="INSERT INTO product(product_name,product_price,product_qty) values('$name','$price','$qty')";
if(mysqli_query($conn, $qry))
{
$data=array("status"=>"1","message"=>"success","result"=>"Product add successfully");
}
else{
$data=array("status"=>"1","message"=>"success","result"=>"Something wrong!!!");
}
break;
case 'PUT':
$id=$_REQUEST['product_id'];
$name=$_REQUEST['product_name'];
$price=$_REQUEST['product_price'];
$qty=$_REQUEST['product_qty'];
$qry="UPDATE product SET product_name='".$name."', product_price='".$price."',product_qty='".$qty."' where product_id='".$id."' ";
if(mysqli_query($conn, $qry))
{
$data=array("status"=>"1","message"=>"success","result"=>"Product Update successfully");
}
else{
$data=array("status"=>"1","message"=>"success","result"=>"Something wrong!!!");
}
break;
case 'DELETE':
$id=$_REQUEST['product_id'];
$qry="delete from product where product_id='".$id."'";
if(mysqli_query($conn, $qry))
{
$data=array("status"=>"1","message"=>"success","result"=>"Product Update successfully");
}
else{
$data=array("status"=>"1","message"=>"success","result"=>"Something wrong!!!");
}
break;
}
echo json_encode($data);
}
else{
$data=array("status"=>"0","message"=>"Please enter proper request method !! ");
echo json_encode($data);
}
}
catch(Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
this is a screenshot of postman while trying DELETE
bear in mind i'm new to this and this is literally my first time working with this !
In the case of PUT and DELETE you need to get the request parameters this way:
$requestParams = array();
parse_str(file_get_contents('php://input'), $requestParams);
Then you can access the values like using $_GET or $_POST:
$requestParams['product_id']
Hope this helps.