<?php
  header("Content-Type: text/html;charset=utf-8");
    $userIp = $_SERVER["REMOTE_ADDR"];
    $timeend = date("H:i:s");
    //时间差
    $sec = strtotime($timeend)-strtotime($_POST[timestart]);
    $m = floor($sec/60);
    $s = floor($sec%60);
    //link to mysql
    $con=mysqli_connect("localhost","buptStudent","buptStudentlx","buptStudentdb");
    if (!$con){die('Could not connect: '.mysql_error());}
    //mysql_select_db("my_db_test", $con);
    //name & student_id
    $chongfu="SELECT Student_ID FROM UserAnswer WHERE Student_ID=$_POST[student_id]";
    if(mysqli_fetch_array(mysqli_query($con,$chongfu))[0]==$_POST[student_id])
    {
      die('对不起，您已参与过本活动。');
    }
    $_SESSION['Student_ID'] = $_POST[student_id];
    $sql="INSERT INTO UserAnswer (user_name, Student_ID, school, userclass, phone, ip, timeend ,timestart, thetime) VALUES ('$_POST[user_name]','$_POST[student_id]','$_POST[school]','$_POST[userclass]','$_POST[telephone]','$userIp','$timeend','$_POST[timestart]','$sec')";
    if (!mysqli_query($con,$sql))
    {
      die("提交失败，请稍后重试。");
    }
    //echo "your name is <strong>".$_POST[user_name]."</strong> and student_id is <strong>".$_POST[student_id]."</strong> .<br />your ip is ".$userIp."<br />开始时间 ".$_POST[timestart]." 结束时间 ".$timeend." 用时 ".$m."分".$s."秒<br />";
    //answer_
    $qn=50;
    for($i=1;$i<=$qn;$i++){
    $a = "answer_".$i;
    //$sql = "UPDATE UserAnswer SET $a=$_POST[$a] WHERE Student_ID=$_POST[student_id]";
    //if (!mysqli_query($sql,$con))
    //  {
    //    $sql2="ALTER TABLE UserAnswer ADD $a INT(11) NOT NULL";
    //    mysqli_query($sql2,$con);
    //    mysqli_query($sql,$con);
    //  }
    $b= "question_".$i;
    //$sql3 = "UPDATE UserAnswer SET $b=$_POST[$b] WHERE Student_ID=$_POST[student_id]";
    //if (!mysqli_query($sql3,$con))
    //  {
    //    $sql4="ALTER TABLE UserAnswer ADD $b INT(11) NOT NULL";
    //    mysqli_query($sql4,$con);
    //    mysqli_query($sql3,$con);
    //  }
    $c= "aq_".$i;
    $d=$_POST[$a]+$_POST[$b]*10;
    $sql5 = "UPDATE UserAnswer SET $c=$d WHERE Student_ID=$_POST[student_id]";
    if (!mysqli_query($con,$sql5))
      {
        $sql6="ALTER TABLE UserAnswer ADD $c INT(11) NOT NULL";
        mysqli_query($con,$sql6);
        mysqli_query($con,$sql5);
      }
    };
    //match & score
    //$result = mysqli_query("SELECT * FROM UserAnswer WHERE Student_ID=$_POST[student_id]");
    //$row = mysqli_fetch_array($result);
    //$g=0;
    //for($i=1;$i<=$qn;$i++){
    //  $b="answer_".$i;
    //  $c=$row[$b];
    //  $d=mysqli_query("SELECT answer FROM Persons WHERE num=$i");
    //  $e=mysqli_fetch_array($d)['answer'];
      //$d=$answer_row[$b];
    //  if($c==$e) $g++;
      //echo "No.".$i." your choice is ".$c." answer is ".$e."<br />";
    //};
    //echo "每题一分： your score is ".$g."<br />";
    //close linking
    mysql_close($con);
    die("提交成功。谢谢参与我们的活动，请继续关注我们公众号bupt_stu的后续推送。现在你可以直接关闭页面了。");
?>