PHP将邮政请求发送到Slim Framework API



我正在使用PHP Slim框架来构建一个API,该API插入,更新和删除并显示存储在MySQL数据库中的数据,现在显示数据工作正常,但是当我尝试插入它时,工作,这是纤细的代码:

$app->post('/api/v1/InsertOrder', function (Request $request, Response $response){
$item_name = $request->getParam("item_name");
$quantity  = $request->getParam("quantity");
$status    = $request->getParam("status");
$sql = "INSERT INTO orders(item_name, quantity, status)VALUES(:item_name, :quantity, :status)";
try {
    $db = DB::connect();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("item_name", $item_name);
    $stmt->bindParam("quantity", $quantity);
    $stmt->bindParam("status", $status);
    $stmt->execute();
    $db = null;
    $res = array("success" => "one row added successfully");
    return json_encode($res);
} catch(PDOException $e) {
    echo '
        {
            "error": {
                "text": '.$e->getMEssage().'
            }
        }
    ';
}

}(;

这是试图插入数据的代码

function CallAPI($method, $api, $data=null) {
$url = "http://localhost/set-api-app/public/api/v1/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
    case 200:
        $error_status = "200: Success";
        return ($data);
        break;
    case 404:
        $error_status = "404: API Not found";
        break;
    case 500:
        $error_status = "500: servers replied with an error.";
        break;
    case 502:
        $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
        break;
    case 503:
        $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
        break;
    default:
        $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
        break;
}
curl_close($curl);
echo $error_status;
die;
}
$data = array('item_name'=>"new item 2",'quantity'=>199,'status'=>"paid2");
$result = CallAPI('POST', "InsertOrder", $data);

上面的代码未插入数据,但是当我使用Web服务客户端时,它可以工作

Content-Type标题设置为application/json,否则Slim无法解码已发布的JSON数据。

相关内容

  • 没有找到相关文章

最新更新