问题运行PHP温度转换器

时间:2011-04-12 14:38:29

标签: php

我一直在尝试使用简单的基于表单的温度转换器,但我目前正在使用白屏,我看不出代码有什么问题。此外,欢迎任何关于最佳实践的想法/建议!

<?php // convert.php

if (isset($_POST['temperature']))   
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

<html>

<head>
    <title>Temperature converter</title>
</head>

<body>
    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    <label>Temperature <input type="text" name="temperature"></label>
    <label>Celcius <input type="radio" name="scale" value="cel"></label>
    <label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>

5 个答案:

答案 0 :(得分:4)

您忘记在第11行的内部if / elseif上使用花括号。它应如下所示:

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah') {
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    }
    elseif ($_POST['scale'] == 'cel') {
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    }
    else
        $output = '';
}

尽量避免使用速记if语法,你可以放弃大括号。

答案 1 :(得分:1)

您的$conv变量仅在if语句中可见。在顶部添加声明:

<?php
$conv = null;
// your code

然后检查if (isset($_POST['submitted']) && $conv !== null)

编辑:正如@halfdan所说,由于你想在if-else子句中执行多个语句,所以缺少大括号。

答案 2 :(得分:1)

你的条件不匹配。

你得到一个空白屏幕,因为解析你的脚本失败并且关闭了错误报告。

答案 3 :(得分:0)

使用$ searchengine查找有关“php white page”的页面,您将获得:

答案 4 :(得分:0)

你的公式也错了。 98.6华氏度转换为37摄氏度 但32摄氏度转换为115华氏度。

那里肯定是错的。

首先,从华氏温度转换为摄氏温度,在乘以9/5之前增加32。那是错的。你必须首先将华氏温度乘以9/5;然后添加32。

所以这一行: $ output = intval((9/5)*($ temp + 32)); 应该是 $ output = intval((9/5)*($ temp)+ 32);

我不知道您希望转换的确切程度,但我也避免使用&#34; intval。&#34;这会将您的转换四舍五入为整数值。