PHP答题类应用接口实例

这篇文章主要介绍了PHP答题类应用接口,以实例形式详细分析了答题类程序的实现思路与相关技巧,并备有较为详尽的注释说明,便于理解,需要的朋友可以参考下。

本文实例讲述了PHP答题类应用接口的实现方法,分享给大家供大家参考,具体实现方法如下:

question_get.php文件如下:

  1. <?php
  2. session_cache_expire(60);
  3. session_start();
  4. if(!isset($_SESSION['zaszh_user_id'])){
  5. echo json_encode(array('status'=>'error','msg'=>'连接超时,请重新打开页面。'));
  6. exit;
  7. }
  8. $user_id = $_SESSION['zaszh_user_id'];
  9. // $user_id = 1; // 测试用
  10. // 随机获取5道问题
  11. $question_id = array();
  12. while(sizeof($question_id)<5){
  13. $num_rand = mt_rand(1,114);
  14. if(!in_array($num_rand, $question_id))
  15. $question_id[] = $num_rand;
  16. }
  17. require('connect_database.php');
  18. // 答题次数
  19. $mysqli->query("update zaszh_user set answer_surplus=answer_surplus-1 where );
  20. if($mysqli->affected_rows){
  21. // 有剩余次数
  22. }else{
  23. // 无剩余次数
  24. echo json_encode(array('status'=>'error','msg'=>'今日答题剩余次数已用完,明天再来哦~'));
  25. $mysqli->close();
  26. exit;
  27. }
  28. // 题目
  29. if($stmt = $mysqli->prepare("select question,A,B,C,D,answer from zaszh_question where id in(?,?,?,?,?)")){
  30. $stmt->bind_param('iiiii',$question_id[0],$question_id[1],$question_id[2],$question_id[3],$question_id[4]);
  31. $stmt->execute();
  32. $stmt->bind_result($question,$A,$B,$C,$D,$answer);
  33. $rows = array();
  34. while($stmt->fetch()){
  35. $rows[] = array(
  36. 'question'=>$question,
  37. 'A'=>$A,
  38. 'B'=>$B,
  39. 'C'=>$C,
  40. 'D'=>$D,
  41. 'answer'=>$answer
  42. );
  43. }
  44. // 答题记录
  45. if($stmt = $mysqli->prepare("insert into zaszh_answer(user_id,question1,question2,question3,question4,question5,create_date) values(?,?,?,?,?,?,unix_timestamp(now()))")){
  46. $stmt->bind_param('iiiiii',$user_id,$question_id[0],$question_id[1],$question_id[2],$question_id[3],$question_id[4]);
  47. $stmt->execute();
  48. if($answer_id = $stmt->insert_id){
  49. $param = array(
  50. 'answer_id'=>$answer_id
  51. );
  52. echo json_encode(array_merge($rows,$param));
  53. }else{
  54. echo json_encode(array('status'=>'error','msg'=>'系统出错。'));
  55. }
  56. }
  57. $stmt->close();
  58. }
  59. $mysqli->close();