如何使用slim获取发布请求数据?

时间:2016-07-23 21:14:17

标签: php sql post slim

这是一个简单的crud应用程序,使用瘦框架我正在使用mysql数据库... slim版本是2.6.2。 Mysql版本是5.7.8

邮递员的形象:

enter image description here

// Adds a customer
function addCustomer() {
    //$request = Slim::getInstance()->request();
    $request = \Slim\Slim::getInstance()->request();
    $cus = json_decode($request->getBody());

    $sql = "INSERT INTO customers (Username,First_Name,Last_Name,Email,Phone,Password,Type,Status) VALUES (:username, :firstname, :lastname, :email, :phone, :password, :type, :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("phone", $cus->Phone);
        $stmt->bindParam("password", $cus->Password);
        $stmt->bindParam("type", $cus->Type);
        $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() .'}}'; 
    }
}

enter image description here

Get request is working fine

获取请求工作正常:

3 个答案:

答案 0 :(得分:1)

我相信你所缺少的是绑定语句中参数之前的冒号。你应该改为:

$stmt->bindParam(":username", $cus->Username);
$stmt->bindParam(":firstname", $cus->First_Name);
$stmt->bindParam(":lastname", $cus->Last_Name);
$stmt->bindParam(":email", $cus->Email);
$stmt->bindParam(":phone", $cus->Phone);
$stmt->bindParam(":password", $cus->Password);
$stmt->bindParam(":type", $cus->Type);
$stmt->bindParam(":status", $cus->Status);

修改

实际上现在我已经深入了解了一下,你用小写的第一个字母传递了params(看看Postman的截图,你使用了用户名,但是在你的代码中,你正在尝试分配用户名)。只需放一个大写的"用户名"作为Postman的帖子字段,或替换如下:

$stmt->bindParam(":username", $cus->username);
$stmt->bindParam(":firstname", $cus->firstname);
$stmt->bindParam(":lastname", $cus->lastname);
$stmt->bindParam(":email", $cus->email);
$stmt->bindParam(":phone", $cus->phone);
$stmt->bindParam(":password", $cus->password);
$stmt->bindParam(":type", $cus->type);
$stmt->bindParam(":status", $cus->status);

编辑II

用以下循环替换所有绑定:

foreach($request->params() as $key => $val) {
    $stmt->bindParam($key, $val);
}

答案 1 :(得分:1)

我认为$ cus->您尝试插入的用户名为空。请尝试使用$ stmt-> bindValue而不是$ stmt-> bindParam。

答案 2 :(得分:1)

这看起来像是区分大小写的问题。您尝试通过对应的数据库列名引用它们的表单中的绑定参数。您的邮递员屏幕截图显示输入名称全部为小写。 尝试     $ stmt-> bindParam("用户名",$ cus->用户名);     $ stmt-> bindParam(" firstname",$ cus-> firstname);     $ stmt-> bindParam("姓氏",$ cus->姓氏);     $ stmt-> bindParam(" email",$ cus-> email);     $ stmt-> bindParam("手机",$ cus->手机);     $ stmt-> bindParam("密码",$ cus->密码);     $ stmt-> bindParam(" type",$ cus-> type);     $ stmt-> bindParam(" status",$ cus-> status);