submitAnswer.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. session_id($_POST['token']);
  3. session_start();
  4. require_once("config.php");
  5. if (!isset($_POST['answers'])) {
  6. $data = [
  7. 'code' => 1000,
  8. 'msg' => 'URL缺少appToken参数'
  9. ];
  10. exit(json_encode($data));
  11. }
  12. if (!isset($_POST['activityID'])) {
  13. $data = [
  14. 'code' => 1001,
  15. 'msg' => 'URL缺少activityID参数'
  16. ];
  17. exit(json_encode($data));
  18. }
  19. $dbLink = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PORT);
  20. $activityID = $_POST['activityID'];
  21. $answers = json_decode($_POST['answers'], true);
  22. $user_id = $_SESSION['userID'];
  23. $rightAnswer = [];
  24. //获取问题列表
  25. $questionSql = "SELECT `id`, `answer` FROM `pingan_question_list` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
  26. //echo $questionSql;
  27. $questionResult = $dbLink->query($questionSql);
  28. $questionCnt = 0;
  29. while ($questionData = $questionResult->fetch_assoc()) {
  30. $questionCnt++;
  31. if (isset($questionData['answer']) && $questionData['answer'] != null) {
  32. $tmpArr = json_decode($questionData['answer'], true);
  33. $rightAnswer[$questionData['id']] = implode(',', $tmpArr);
  34. }
  35. }
  36. $questionResult->free();
  37. $selections = "";
  38. $customInput = "";
  39. $rightCount = 0;
  40. for ($i = 1; $i <= count($answers); ++$i) {
  41. $obj = $answers[$i];
  42. $questionID = $obj['id'];
  43. if (isset($obj['options'])) {
  44. $an = implode(',', $obj['options']);
  45. $selections .= $an;
  46. if (strcmp($rightAnswer[$questionID], $an) == 0) {
  47. $rightCount++;
  48. }
  49. $selections .= ';';
  50. } else if (isset($obj['input'])) {
  51. $customInput = $obj['input'];
  52. if (mb_strlen($customInput, "utf-8") > 0) {
  53. $rightCount++;
  54. }
  55. }
  56. }
  57. $updateSql = 'UPDATE `pingan_user_info` SET `options` = ?, `custom_input` = ? WHERE `user_id` = ? AND `activity_id` = ?';
  58. if (!($stmt = $dbLink->prepare($updateSql))) {
  59. echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
  60. }
  61. $stmt->bind_param("ssii", $selections, $customInput, $user_id, $activityID);
  62. $stmt->execute();
  63. $_SESSION['hasAnswerRight_' . $activityID] = ($rightCount == $questionCnt) ? 1 : 0;
  64. $data = [
  65. 'code' => 200,
  66. 'data' => [
  67. 'lottery' => ($rightCount == $questionCnt),
  68. 'rightCount' => $rightCount
  69. ]
  70. ];
  71. echo json_encode($data);