首页 > 解决方案 > 使用 HTML 表单和 PHP 函数进行温度转换

问题描述

我正在尝试使用 php 转换 deg -> c 和 c -> deg。目标是使用包含公式的函数,然后使用带有单选按钮和文本框的表单。用户应该能够在文本框中输入学位,单击他们选择的单选按钮(F 或 C),然后提交表单以接收他们的转换。我看过类似的帖子,但方法并不特定于我遇到的问题。

我已经更新了我的代码,但现在出现“死亡白页” 任何人都可以看到我看不到的错误吗?谢谢!

HTML

<h1>Temperature Conversion</h1>



<form action='lab_exercise_6.php' method ='POST'>
    <p>Enter a temp to be converted and then choose the conversion type below.</p>

<input type ='text' maxlength='3' name ='calculate'/>

 <p>Farenheit
  <input type="radio" name='convertTo' value="f" />
</p>

<p>Celsius
  <input type="radio" name='convertTo' value="c" />
</p>

<input type='submit' value='Convert Temperature' name='convertTo'/>

PHP

<?php

//function 1

function FtoC($deg_f) {
    return ($deg_f - 32) * 5 / 9;
  }

  //function 2
function CtoF($deg_c){
    return($deg_c + 32) * 9/5;
}

if( isset($_POST['convertTo']) && $_POST['convertTo'] ==="c" ){
$farenheit = FtoC($deg_f);
print('This temperature in FARENHEIT is equal to ' . $celsius . ' degrees celsius! </br>');
}else if(isset($_POST['convertTo'])&& $_POST['convertTo']==='f'){
    $celsius = CtoF($deg_c);
    print('This temperature in CELSIUS is equal to ' . $farenheit . ' degrees farenheit! </br>');

}

?>

标签: phphtml

解决方案


正是这部分使其表现出乎意料:

$farenheit = FtoC($deg_f);
// And then a few lines lower:
if(isset($farenheit)){ /* ... */}

您在此处将其设置为一个值,因此它将始终尝试计算结果。
稍作调整,您将更多地使用单选按钮:

<input type="radio" name="convertTo" value="f" />
<input type="radio" name="convertTo" value="c" />

PHP 中的值现在将始终具有相同的名称,您现在可以检查它的值:

if( isset($_POST['convertTo']) && $_POST['convertTo']==="c" ){
    $farenheit = FtoC($deg_f);
    print('This temperature in FARENHEIT is equal to ' . $celsius . ' degrees celsius! </br>');
}

推荐阅读