本文實例講述了PHP答題類應用接口的實現方法。分享給大家供大家參考。具體實現方法如下:
question_get.php文件如下:
復制代碼 代碼如下:<?php
session_cache_expire(60);
session_start();
if(!isset($_SESSION['zaszh_user_id'])){
echo json_encode(array('status'=>'error','msg'=>'連接超時,請重新打開頁面。'));
exit;
}
$user_id = $_SESSION['zaszh_user_id'];
// $user_id = 1; // 測試用
// 隨機獲取5道問題
$question_id = array();
while(sizeof($question_id)<5){
$num_rand = mt_rand(1,114);
if(!in_array($num_rand, $question_id))
$question_id[] = $num_rand;
}
require('connect_database.php');
// 答題次數
$mysqli->query("update zaszh_user set answer_surplus=answer_surplus-1 where id={$user_id} and answer_surplus>0");
if($mysqli->affected_rows){
// 有剩余次數
}else{
// 無剩余次數
echo json_encode(array('status'=>'error','msg'=>'今日答題剩余次數已用完,明天再來哦~'));
$mysqli->close();
exit;
}
// 題目
if($stmt = $mysqli->prepare("select question,A,B,C,D,answer from zaszh_question where id in(?,?,?,?,?)")){
$stmt->bind_param('iiiii',$question_id[0],$question_id[1],$question_id[2],$question_id[3],$question_id[4]);
$stmt->execute();
$stmt->bind_result($question,$A,$B,$C,$D,$answer);
$rows = array();
while($stmt->fetch()){
$rows[] = array(
'question'=>$question,
'A'=>$A,
'B'=>$B,
'C'=>$C,
'D'=>$D,
'answer'=>$answer
);
}
// 答題記錄
if($stmt = $mysqli->prepare("insert into zaszh_answer(user_id,question1,question2,question3,question4,question5,create_date) values(?,?,?,?,?,?,unix_timestamp(now()))")){
$stmt->bind_param('iiiiii',$user_id,$question_id[0],$question_id[1],$question_id[2],$question_id[3],$question_id[4]);
$stmt->execute();
if($answer_id = $stmt->insert_id){
$param = array(
'answer_id'=>$answer_id
);
echo json_encode(array_merge($rows,$param));
}else{
echo json_encode(array('status'=>'error','msg'=>'系統出錯。'));
}
}
$stmt->close();
}
$mysqli->close();
希望本文所述對大家的php程序設計有所幫助。