我正在为我制作的简单数学游戏编写难度脚本。我创建了一个html表单,用户可以从1到5输入难度,通过if函数相应地分配难度。这可以正常工作但是在会话开始时难度变量尚未设置,这对于if函数没有问题,因为它以一个难以分配的else选项结束,使得游戏的默认难度为1.但是我我留下了未定义的变量错误,即使变量还需要调用。这是我写的,我似乎找不到解决这个问题的方法。
session_start();
echo ('<h2>Change Difficulty (1 to 5)</h2>' . '<br/>');
echo "<form method = 'post'><input type='text' id='random' name='random' onChange='preventDefault();'></form>";
if(isset($_POST['random'])) {
if ($_POST['random'] == 1 or $_SESSION['diffculty'] == 1) {
$randvalue = 10;
echo 'Current Difficulty Is 1';
$diffculty = 1;
} elseif($_POST['random'] == 2 or $_SESSION['diffculty'] == 2) {
$randvalue = 100;
echo 'Current Difficulty Is 2';
$diffculty = 2;
} elseif($_POST['random'] == 3 or $_SESSION['diffculty'] == 3) {
$randvalue = 1000;
echo 'Current Difficulty Is 3';
$diffculty = 3;
} elseif($_POST['random'] == 4 or $_SESSION['diffculty'] == 4) {
$randvalue = 10000;
echo 'Current Difficulty Is 4';
$diffculty = 4;
} elseif($_POST['random'] == 5 or $_SESSION['diffculty'] == 5) {
$randvalue = 100000;
echo 'Current Difficulty Is 5';
$diffculty = 5;
} else {
$randvalue = 10;
echo 'current Difficulty is 1';
$diffculty = 1;
}
$_SESSION['randvalues'] = $randvalue;
$_SESSION['difficulty'] = $diffculty;
}
即使用户设置难度变量,即使分配了if变量,也会在if函数中调用的每行代码都会得到未定义的索引错误。
答案 0 :(得分:0)
对会话应用isset并首先添加else case。
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
echo ('<h2>Change Difficulty (1 to 5)</h2>' . '<br/>');
echo "
<form method = 'post'>
<input type='text' id='random' name='random' onChange='preventDefault();'>
</form>";
if(isset($_POST['random']) && isset($_SESSION['diffculty'])) {
if ($_POST['random'] == 1 or $_SESSION['difficulty'] == 1) {
$randvalue = 10;
echo 'Current Difficulty Is 1';
$difficulty = 1;
} elseif($_POST['random'] == 2 or $_SESSION['difficulty'] == 2) {
$randvalue = 100;
echo 'Current Difficulty Is 2';
$difficulty = 2;
} elseif($_POST['random'] == 3 or $_SESSION['difficulty'] == 3) {
$randvalue = 1000;
echo 'Current Difficulty Is 3';
$difficulty = 3;
} elseif($_POST['random'] == 4 or $_SESSION['difficulty'] == 4) {
$randvalue = 10000;
echo 'Current Difficulty Is 4';
$difficulty = 4;
} elseif($_POST['random'] == 5 or $_SESSION['difficulty'] == 5) {
$randvalue = 100000;
echo 'Current Difficulty Is 5';
$difficulty = 5;
} else {
$randvalue = 10;
echo 'current Difficulty is 1';
$difficulty = 1;
}
$_SESSION['randvalues'] = $randvalue;
$_SESSION['difficulty'] = $difficulty;
} else {
$_SESSION['randvalues'] = 10;
$_SESSION['difficulty'] = 1;
}
答案 1 :(得分:0)
使用全局变量$_SERVER['PHP_SELF']
echo "<form method = 'post'><input action=".$_SERVER['PHP_SELF']."type='text' id='random' name='random' onChange='preventDefault();'></form>";