我不明白为什么我的函数没有得到结果而只是获得null值。我正在使用PhpStorm;我所有的连接都很好(Apache,MySQL,PhpMyAdmin)我检查过它们,其他服务也正常工作。
这是我的dbhandler.php
文件:
public function getRating($rating_id, $user_id) {
$stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?");
$stmt->bind_param("ii", $rating_id, $user_id);
if ($stmt->execute()) {
$stmt->bind_result( $restaurant_id, $service_rating, $food_rating, $music_rating);
// TODO
//$rating_id = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res = array();
$res["user_id"] = $user_id;
$res["rating_id"] = $rating_id;
$res["restaurant_id"] = $restaurant_id;
$res["service_rating"] = $service_rating;
$res["food_rating"] = $food_rating;
$res["music_rating"] = $music_rating;
$stmt->close();
return $res;
} else {
return NULL;
}
}
这是我的index.php
文件
$app->get('/userRatings/:rating_id', 'authenticate', function($rating_id) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch rating
$result = $db->getRating($rating_id, $user_id);
if ($result != NULL) {
$response["user_id"] = $result["user_id"];
$response["rating_id"] = $result["rating_id"];
$response["restaurant_id"] = $result["restaurant_id"];
$response["service_rating"] = $result["service_rating"];
$response["food_rating"] = $result["food_rating"];
$response["music_rating"] = $result["music_rating"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
请求的响应是:
{"user_id":19,
"rating_id":"171",
"restaurant_id":null,
"service_rating":null,
"food_rating":null,
"music_rating":null}
答案 0 :(得分:2)
param值存在问题。更改参数值如下。
$stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?");
$stmt->bind_param("ii", $user_id,$rating_id);
根据你的sql第一个param应该是$ user_id。不是$ rating_id。
根据您的参数设置,没有要获取的记录。