forked from jasonhillinger/Mini-Stackoverflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bestAns.php
59 lines (52 loc) · 2.17 KB
/
bestAns.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
include_once 'server.php';
session_start();
$errors = array();
$response = [];
$best = $_POST['best'];
$answerID = $_POST['answerID'];
//fetch questionID of reference question for the answer
$fetchRefQuestionQuery = "SELECT answers.refQuestion FROM answers WHERE answers.answerID = $answerID;";
$questionRes = mysqli_query($db, $fetchRefQuestionQuery);
$refQuestion = mysqli_fetch_assoc($questionRes);
$questionID = $refQuestion['refQuestion'];
mysqli_free_result($questionRes);
//fetch the data from the database for this question to check if it already has a best answer
$fetchBestQuery = "SELECT bestAnswer FROM questions WHERE questionID = $questionID;";
$bestRes = mysqli_query($db, $fetchBestQuery);
$bestAns = mysqli_fetch_assoc($bestRes);
mysqli_free_result($bestRes);
function setBest($aID, $qID, $Best, $db){
// Best can be either 0 or 1
// the user who is logged in must have the same userID as the poster to be able to set best answer
//this fucntion sets the answer as bestanswer for corresponding question and for answer itself
if ($Best == 1){
$isBestQuery = "UPDATE answers SET isBest = 1 WHERE answerID = $aID";
$bestAQuery = "UPDATE questions SET bestAnswer = $aID WHERE questionID = $qID";
mysqli_query($db,$isBestQuery);
mysqli_query($db,$bestAQuery);
}
elseif($Best == 0){
$isBestQuery = "UPDATE answers SET isBest = 0 WHERE answerID = $aID";
$bestAQuery = "UPDATE questions SET bestAnswer = NULL WHERE questionID = $qID";
mysqli_query($db,$isBestQuery);
mysqli_query($db,$bestAQuery);
}
}
if (is_null($bestAns['bestAnswer'])){
setBest($answerID, $questionID, $best, $db);
$response['status'] = "Marked answer as best answer.";
$response['success'] = "true";
}
elseif ($best==0){
setBest($answerID, $questionID, $best, $db);
$response['status'] = "Unmarked best answer.";
$response['success'] = "true";
}
else{
$response['status'] = "Cannot mark two answers as best answer for same question.";
$response['success'] = "false";
}
header('Content-type: application/json');
echo (json_encode($response));
?>