我正在为我的Android应用程序开发REST API。目前我还没有把它放到我的应用程序中,而是试图用Chrome上流行的“高级休息客户端应用程序”进行测试。处理GET方法的函数工作正常,并以json格式显示我的数据库中的记录,但是当我尝试测试函数处理POST时,它不起作用。我想请一些人帮我解决如何从“高级休息客户端应用程序”测试我的帖子功能。
API代码:
<?php
require_once '../include/DbConnect.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
// create new Slim instance
$app = new \Slim\Slim();
$app->get('/users', 'getUser');
$app->post('/register', 'addUser');
$app->run();
function getUser(){
$sql = "SELECT * FROM users";
try{
$db = new DbConnect();
$conn = $db->connect();
$stmt = $conn->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"user": ', json_encode($users).'}';
} catch(PDOException $e){
echo '{"error":{"text":'. $e->getMessage().'}}';
}
}
function addUser() {
$request = \Slim\Slim::getInstance()->request();
$body = $request->getBody();
$user = json_decode($body);
$sql = "INSERT INTO users (fname, email) VALUES(:fname, :email)";
try{
$db = new DbConnect();
$conn = $db->connect();
$stmt = $conn->prepare($sql);
$stmt->bindParam("fname", $user->fname);
$stmt->bindParam("email", $user->email);
$stmt->execute();
$user->id = $conn->lastInsertId();
$db = null;
echo json_encode($user);
} catch(PDOException $e){
echo '{"error":{"text":'. $e->getMessage().'}}';
}
}
?>
答案 0 :(得分:0)
好的,这是我的问题,当我在下面的代码中回显$ body的内容时,这些值显示为“fname = mishael&amp; email = mishaelharry%40gmail.com”,但在用$ user = json_decode解码之后($机构);没有值插入我的数据库,我得到{“fname”:null,“email”:null,“id”:“33”}来自这行代码echo json_encode($ user); [代码]
function addUser() {
$request = \Slim\Slim::getInstance()->request();
$body = $request->getBody();
echo json_encode($body);
$user = json_decode($body);
$sql = "INSERT INTO users (fname, email) VALUES(:fname, :email)";
try{
$db = new DbConnect();
$conn = $db->connect();
$stmt = $conn->prepare($sql);
$stmt->bindParam("fname", $user->fname);
$stmt->bindParam("email", $user->email);
$stmt->execute();
$user->id = $conn->lastInsertId();
$db = null;
echo json_encode($user);
} catch(PDOException $e){
echo '{"error":{"text":'. $e->getMessage().'}}';
}
}