我正在尝试一个简单的Rest api,GET和POST方法可以工作,但是当我尝试测试显示PUT和DELETE Undefined Index
错误并显示数据库没有更新时,我尝试输入数据通过form-data
和raw
以及x-www-form-urlencoded
,但没什么
当我手动将数据输入代码而不是$_REQUEST
时,它就可以正常工作
这是我的代码:
<?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
请记住,我对此并不陌生,这实际上是我第一次使用它!
答案 0 :(得分:0)
对于PUT和DELETE,您需要通过以下方式获取请求参数:
$requestParams = array();
parse_str(file_get_contents('php://input'), $requestParams);
然后,您可以使用$ _GET或$ _POST来访问值:
$requestParams['product_id']
希望这会有所帮助。