php - PHP测验无法正常工作
问题描述
我正在尝试做一个简单的 php 测验,但我必须插入答案并将它们与 strcasecmp() 进行比较,所以如果第一个字母是大写或类似的,则不会有问题,但代码没有'不能正常工作。有时它不会返回正确的结果,即使我插入了正确的答案。这是代码:
<?php
$number = rand(1,2);
$result = "";
$answer = "";
$question = "";
$question1 = "What is the capital of China";
$question2 = "What king of country is China?";
$answer1 = "beijing";
$answer2 = "republic";
if ($number == 1) {
$answer = $answer1;
$question = $question1;
}
if ($number == 2) {
$answer = $answer2;
$question = $question2;
}
if(isset($_POST['submit'])){
if (strcasecmp($answer,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Wrong!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="index.php">
<div class="middle">
<p class="question"><?php echo $question;
?></p>
<p class="result"><?php echo $result;
$result = "" ?></p>
<div class="box">
<input type="text" name="answer" placeholder="Type here" class="text">
</div>
</div>
<input type="submit" name="submit" value="Continue" class="btn">
</form>
</body>
</html>
解决方案
通过查看您的代码,我们可以看到,当您提交表单时,您正在重新启动脚本,该脚本实际上会重置$random
为新值。有 2 个问题,你有 50% 的机会得到“正确”的答案,但你会发现你的脚本在添加更多问题时根本不起作用。
基本上,您应该使用另一种方式来实现您想要的。您可以尝试在隐藏中添加问题的 id,<input>
并检查您的表单何时提交以确定它是哪一个。
if(isset($_POST['submit'])){
switch ($_POST['question']) { // Add '{'
case 1:
if (strcasecmp($answer1,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
}
break;
case 2:
if (strcasecmp($answer2,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
} // Forgot to Add '}'
break;
} // Add '}' It give error in PHP 5.3 Parse error: syntax error, unexpected T_CASE, expecting ':' or '{'
}
对于 HTML,您可以在表单中添加此输入:
<input type="text" name="question" value="<?php echo $number ?>" hidden>
这不是实现您想要的最佳方式,这只是可行的示例。
推荐阅读
- nginx - NGINX try_files 不接受文件名。无论我做什么,它都会强制尝试打开 $uri
- javascript - 找到特定文本时如何使页面刷新?
- laravel - Laravel8 - Vue3 显示存储中的图像
- list - Scala containsSlice 实现
- python - 如何在 TensorFlow 中训练 3D 数组
- reactjs - Cypress 组件测试、ReactJS 和 TailwindCSS
- ruby-on-rails - Linux mint mate - ruby 3.0.2 - zlib.so 未定义符号:inflateReset
- git - 无法将新更新推送到远程
- api - 如何使用 CoinMarketCap api 仅请求一种加密货币的数据?
- reactjs - 试图通过渲染器在 reactjs 中发出警报