我正在进行某种'测验'。用户被问到一个问题,可以在三个答案之间进行选择。这是我的代码:
// query
$result = mysql_query("SELECT * FROM `db_game` LEFT JOIN `db_game_printers` ON (db_game.printerId = db_game_printers.id) ORDER BY RAND() LIMIT 1") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
// explode answers
$row['printerQuestion'] = trim($row['printerQuestion']);
$question = explode(",", $row['printerQuestion']);
$printerQuestion = $row['title'];
$printerAnswer = $row['printerAnswer'];
// check answer
$answer = $row['printerAnswer'];
if (isset($_GET['answer'])) {
$answerUser = $_GET['answer'];
if ($answerUser == $answer) {
$correct = true;
} else {
$false = true;
}
}
它按预期工作。当用户通过单击答案回答问题时,将显示下一个问题。我还想表明他们是否真的回答正确或不正确!我写了这段代码:
<div id="wrapper">
<div id="question">
<h1><?= $printerQuestion; ?></h1>
</div><!-- /question -->
<ul id="answers">
<li style="text-align:left;"><a href="index.php?answer=<?=$question[0];?>"><button class="punch"><?=$question[0];?></button></a></li>
<li style="text-align:center;"><a href="index.php?answer=<?=$question[1];?>"><button class="punch"><?=$question[1];?></button></a></li>
<li style="text-align:right;"><a href="index.php?answer=<?=$question[2];?>"><button class="punch"><?=$question[2];?></button></a></li>
</ul>
<div class="clear" style="margin-bottom:50px;"></div>
<?php
$prev_printerQuestion = $printerQuestion;
$prev_printerAnswer = $printerAnswer;
} // end while loop
?>
<?php
if (isset($_GET['answer'])) {
if ($correct) {
echo "Correct! The ".$prev_printerQuestion." uses the ".$prev_printerAnswer."";
}
else if ($false) {
echo "Not correct. ".$prev_printerQuestion." = ".$prev_printerAnswer."" ;
}
}
?>
</div><!-- /wrapper -->
检查答案是否正确使用当前数据。不是上一个问题。我尝试将值放在单独的变量中以及在while循环的外部(和内部),但它没有区别。
有人有任何想法吗?
答案 0 :(得分:2)
首先,定义一些函数来表示您在应用程序中尝试执行的操作。 (我将停止使用这里的功能而不是谈论OO原则,以保持简单)。
了解应用程序功能的封装是良好软件设计的第一步。
在您的情况下,您的视图层非常简单:
function displayQuestion($question, $answers) { /* display html for question and possible answers */ }
要显示问题,您需要从数据库中获取问题及其答案。你可以这样做:
function getQuestion($questionNumber) { /* performs SQL queries and returns some representation of question, answers and correct answer */ }
然后你拥有真正的“商业”(游戏)逻辑本身,即:
function checkAnswer($questionNumber, $answerGiven) { /* returns true or false */ }
你还需要一些功能来控制整个游戏,可能就像:
function startNewGame() { /* reset internal variables */ }
function getCurrentQuestionNumber() { /* get the question that the user is up to */ }
function displayCurrentScore() { /* display html for current score */ }
最后一部分是将它们连接在一起。 (我的意思是讨论中的最后一个,而不是你做的最后一件事)。这是将各部分连接在一起的地方,从HTTP请求开始,再到模型和业务逻辑,再返回视图层,通过HTTP响应向用户显示页面。您可以想象将整个过程封装为一种方法:
function handleRequest() { /* perform the whole request-response cycle, calling the other methods as required */ }
请注意,以上只是对这些功能及其功能的广泛而相当通用的方法,我不知道您的确切要求,因此会丢失部件。它也不是“最佳实践”,但它比将您的业务逻辑和数据库访问混合到您的HTML代码更好: - )