这是一个简单的crud应用程序,使用瘦框架我正在使用mysql数据库... slim版本是2.6.2。 Mysql版本是5.7.8
邮递员的形象:
// 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() .'}}';
}
}
获取请求工作正常:
答案 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)