简体   繁体   English

PHP发送请求到苗条的框架API

[英]php sending post request to slim framework api

I'm using php slim framework to build an api that insert and update and delete and show data stored in mysql database, now displaying data is working fine but when i try to insert it doesnt work, this is slim code: 我正在使用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().'
            }
        }
    ';
}

}); });

and here's the code that tries to insert data 这是尝试插入数据的代码

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);

the above code doesn't insert data however when i use web service client it works 上面的代码没有插入数据,但是当我使用Web服务客户端时,它可以工作

Content-Type标头设置为application/json ,否则Slim无法解码POST的JSON数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM