调用get后,PHP Slim API返回null

时间:2016-04-06 07:58:58

标签: mysql angularjs api slim postman

我在Postman中运行以下代码,但我的所有字段都以null结尾。我用echo json_encode($ cus)来看这个。我一直在摆弄几个小时,但我不确定我的错误在哪里。任何帮助将不胜感激!

require 'Slim/Slim.php';

$app = new Slim();

$app->get('/Customers', 'getCustomers');
$app->get('/Customers/:id', 'getCustomer');
$app->post('/New_Customer', 'addCustomer');
$app->put('/Customers/:id', 'updateCustomer');
$app->delete('/Customers/:id', 'deleteCustomer');

$app->run();


// Add new Customer to the Database
function addCustomer() {
    $request = Slim::getInstance()->request();
    $cus = json_decode($request->getBody());

    $sql = "INSERT INTO customers (Username, First_Name, Last_Name, Email, Status) VALUES (:username, :firstname, :lastname, :email, :status)";
    try {
        $db = DB_Connection();
        $stmt = $db->prepare($sql);  
        $stmt->bindParam("username", $cus->Username);
        $stmt->bindParam("firstname", $cus->First_Name);
        $stmt->bindParam("lastname", $cus->Last_Name);
        $stmt->bindParam("email", $cus->Email);
        $stmt->bindParam("status", $cus->Status);
        $stmt->execute();
        $cus->id = $db->lastInsertId();
        $db = null;
        echo json_encode($cus); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
        //echo json_encode($cus);
    }
}

修改

var_dump($cus) results in
object(stdClass)#18 (5) { ["Username"]=> &NULL ["First_Name"]=> &NULL ["Last_Name"]=> &NULL ["Email"]=> &NULL ["Status"]=> &NULL 

在POSTMAN中我使用的是form-data和x-www-form-urlencoded。

2 个答案:

答案 0 :(得分:0)

(你的版本是什么?)

我看着我苗条的

你的

$request = Slim::getInstance()->request();

我的:版本2.4.2

$request = \Slim\Slim::getInstance()->request();

答案 1 :(得分:0)

由于您正在执行JSON API请求,因此必须使用Content-Type: application/json而不是Content-Type: application/x-www-form-urlencode