【问题标题】:PHP Slim API returns null after calling getPHP Slim API 调用 get 后返回 null
【发布时间】:2016-04-07 11:36:59
【问题描述】:

我在 Postman 中运行以下代码,但我的所有字段最终都为空。我用 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。

【问题讨论】:

  • var_dump($cus) 查看您获得的实际值。
  • 你在 POSTMAN 中使用什么内容类型......
  • var_dump($cus) 结果为 object(stdClass)#18 (5) { ["Username"]=> &NULL ["First_Name"]=> &NULL ["Last_Name"]=> &NULL [ "电子邮件"]=> &NULL ["状态"]=> &NULL
  • 在 POSTMAN 中,我使用的是 form-data 和 x-www-form-urlencoded。

标签: mysql angularjs api slim postman


【解决方案1】:

(你的版本是什么?)

我看看我的苗条

你的

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

我的:版本 2.4.2

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

【讨论】:

    【解决方案2】:

    由于你在做 JSON API 请求,所以必须使用Content-Type: application/json 而不是Content-Type: application/x-www-form-urlencode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多