我对php和mySQL还是很陌生。我正在编写一个需要占用和释放位置的程序,我做的方法是制作一个名为“ spaces”的表,它具有“ id”和“ occupied_by”(占用该位置的用户)作为属性。我将“ occupied_by”的默认值设置为NULL,这样我就知道空间是否被占用。 我编写了占用Spots的代码,并且效果很好。但是我总是在代码错误上清空它们
在constrants.php文件中,我有这些
define ('SUCCESS', 301);
define ('FAIL', 302);
define ('FREE', 303);
然后在operations.php文件中,我有此代码
public function freeSpot($id){
if(!$this->isOccupied($id)){
return FREE;
}
else {
$stmt = $this->con->prepare("UPDATE spaces SET occupied_by = NULL WHERE id = ?");
$stmt->bind_param("ss", $occupiedBy, $id);
if ($stmt->execute()){
return SUCCESS;
}else{
return FAIL;
}
}
}
private function isOccupied($id){
$query = $this->con->prepare("SELECT occupied_by FROM spaces WHERE (id = ?) LIMIT 1");
$query->bind_param("s", $occupiedBy);
$query->bind_result($occupy);
$query->execute();
$query->store_result();
return $query->num_rows > 0;
}
,在我用来检查POSTMAN上的代码的index.php文件中,我有以下代码:
$app->post('/freeSpot/{id}', function (Request $request, Response $response) {
$pSpaceId = $request->getAttribute('id');
$requestData = $request->getParsedBody();
// $occupiedBy = $requestData['occupied_by'];
$db = new DbOperations();
$result = $db->freeSpot($id);
$responseData = array();
if ($result == SUCCESS) {
$responseData['error'] = false;
$responseData['message'] = 'spot emptied successfully';
$response->write(json_encode($responseData));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else if($result == FAIL) {
$responseData['error'] = true;
$responseData['message'] = 'Could not empty';
$response->write(json_encode($responseData));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
}
else if($result == FREE){
$responseData['error'] = true;
$responseData['message'] = 'spot is already empty';
$response->write(json_encode($responseData));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
无论我输入什么ID,它都会告诉我“ spot已经为空”,而不是。怎么了?