我正在尝试使用表单和PHP并使用SWITCH案例制作温度转换器。我相信我已经接近解决方案,但是当我按下“提交”按钮时,我的页面变成空白,并且看不到echo语句。这是我的代码:
<?php
if(isset($_POST['convertTemp']))
{
switch('$convertTemp'){
case 'FtoC':
$newTemp = (($tEmp - 32)* (5/9));
break;
case 'FtoK':
$newTemp = (($tEmp - 32)* (5/9) + 273.15);
break;
case 'KtoF':
$newTemp = (($tEmp - 273.15)* (9/5) + 32);
break;
case 'KtoC':
$newTemp = ($tEmp - 273.15);
break;
case 'CtoK':
$newTemp = ($tEmp + 273.15);
break;
case 'CtoF':
$newTemp = (($tEmp * 9/5) + 32);
break;
echo " <h2 align='center'>The initial temperature was" . $tEmp . "and the converted temperature is:" . $newTemp . "/h2>";
}
}else{
echo'
<html>
<body>
<h1 align="center">Convert a Temperature</h1>
<form align="center" method="POST">
Enter the tempurature you wish to convert:<input type="number" name="tEmp">
<h2>Convert temperature from: </h2>
<input type="radio" name="convertTemp" value="FtoC"> Farenheit to Celcius <br>
<input type="radio" name="convertTemp" value="FtoK"> Farenheit to Kelvin <br>
<input type="radio" name="convertTemp" value="KtoF"> Kelvin to Farenheit <br>
<input type="radio" name="convertTemp" value="KtoC"> Kelvin to Celcius <br>
<input type="radio" name="convertTemp" value="CtoK"> Celcius to Kelvin <br>
<input type="radio" name="convertTemp" value="CtoF"> Celcius to Farenheit <br>
<input type="submit" value="Convert Tempurature!">
</form>
</body>
';
}
?>
答案 0 :(得分:0)
这里有几个问题。您未看到的echo
在最后一个switch
之后的break
语句中,需要在切换之后(即switch
的右括号之后)出现声明)。但是,即使这样做,也不会设置变量(未设置$tEmp
,您需要先从$_POST
获取其值,与$convertTemp
相同)。
<?php
if(isset($_POST['convertTemp']) && isset($_POST['tEmp'])) {
$convertTemp = $_POST['convertTemp'];
$tEmp = $_POST['tEmp'];
switch($convertTemp){
case 'FtoC':
$newTemp = (($tEmp - 32)* (5/9));
break;
case 'FtoK':
$newTemp = (($tEmp - 32)* (5/9) + 273.15);
break;
case 'KtoF':
$newTemp = (($tEmp - 273.15)* (9/5) + 32);
break;
case 'KtoC':
$newTemp = ($tEmp - 273.15);
break;
case 'CtoK':
$newTemp = ($tEmp + 273.15);
break;
case 'CtoF':
$newTemp = (($tEmp * 9/5) + 32);
break;
}
echo "<h2 align='center'>The initial temperature was " . $tEmp . " and the converted temperature is: " . $newTemp . "</h2>";
}
else {
echo'
<html>
<body>
<h1 align="center">Convert a Temperature</h1>
<form align="center" method="POST">
Enter the tempurature you wish to convert:<input type="number" name="tEmp">
<h2>Convert temperature from: </h2>
<input type="radio" name="convertTemp" value="FtoC"> Farenheit to Celcius <br>
<input type="radio" name="convertTemp" value="FtoK"> Farenheit to Kelvin <br>
<input type="radio" name="convertTemp" value="KtoF"> Kelvin to Farenheit <br>
<input type="radio" name="convertTemp" value="KtoC"> Kelvin to Celcius <br>
<input type="radio" name="convertTemp" value="CtoK"> Celcius to Kelvin <br>
<input type="radio" name="convertTemp" value="CtoF"> Celcius to Farenheit <br>
<input type="submit" value="Convert Tempurature!">
</form>
</body>
</html>
';
}
?>