简体   繁体   中英

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:

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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