如果匹配随机任务,请检查给出的答案答案

时间:2012-07-17 13:12:33

标签: php

您好我正在使用此代码生成随机问题:

<?php
session_start(); //this was missing from this file
//connect to db
require_once('db_conn.php');

$id=rand(0,13); //2nd number = highest ID

if ($res = $mysqli->query("SELECT quest FROM table WHERE ID='$id'")){

   $resQ = $res->fetch_assoc(); 
   echo "" . $resQ['quest'] . "";

   $_SESSION['chckanswer'] = $resQ['guest'];

   $res->close();
}
$mysqli->close();
?>

这个尝试检查给出的答案是否符合问题:

<?php
session_start();

//more code

if($stmt = $mysqli->prepare('SELECT quest FROM table WHERE answer=?')){
    $stmt->bind_param("s", $_POST['given_answer']);
    $stmt->execute();
    $stmt->bind_result($quest);
    $stmt->fetch();

        if($_SESSION['chckanswer'] != $quest && !empty($_SESSION['chckanswer'])){
        echo 'wrong';
        exit();
        }
        else{
        echo 'ok';
        }
    $stmt->close();    
}
//more code

但我收到错误未定义索引chckanswer

2 个答案:

答案 0 :(得分:0)

$id=rand(0,13); // 0-13

我认为没有id为“零”的行

isset($_SESSION['chckanswer']) ? $_SESSION['chckanswer'] : null;

添加此行

答案 1 :(得分:0)

第一个文件中缺少这个:

session_start();