【发布时间】:2016-06-19 06:46:25
【问题描述】:
我正在尝试制作一个 REST API,它使用 POST 在我的数据库中创建一个新对象。我正在使用 Slim 框架。
问题在于我不确定在我的POST 方法的这些行中到底需要添加什么:
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode(**Here they put the name of the type of the object that they have in their database**));
我的完整POST 路线是:
$app->post("/cars/", function() use($app)
{
$idCar = $app->request->post("idCar");
$name = $app->request->post("name");
try{
$connection = getConnection();
$dbh = $connection->prepare("INSERT INTO cars VALUES(?,?)");
$dbh->bindParam(1,$idCar);
$dbh->bindParam(2,$name);
$dbh->execute();
$connection = null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode(**What I have to put here?**));
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
});
在表cars中有对象Car。
我应该这样写吗?:
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($Car));
我有点困惑,因为在我之前看到的教程中,在POST 方法中,它们没有对POST 路由内的变量名称的任何引用。例如,如果他们使用$fruit,他们没有在他们的路由中声明任何名为$fruit 的变量。
我该怎么办?我的回答正确吗?
【问题讨论】:
-
phpmyadmin不是数据库。 MYSQL 是 `phpMyAdmin' 可以用来查看和操作的数据库!!! -
我建议您应该返回某种状态信息,告诉调用者该过程正确完成或失败。但是,您不会从数据库访问代码中检查任何状态,因此即使您实际上也不知道它是否成功
-
@RiggsFolly 对不起,我是这个领域的新手。你知道我在我有疑问的地方放了什么吗?谢谢你的指正!
-
@RiggsFolly 我只想使用 Android 中的
POST方法。会有所不同吗? (我看到的教程是使用Slim framework和Android。 -
您是否设置了连接以生成异常?即
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
标签: php rest post httpresponse slim