在PHP中将摄氏温度转换为华氏温度和反之亦然值

时间:2017-03-09 21:42:19

标签: php html function

我是PHP的新手,我正在尝试编写两个将Celsius转换为Fahrenheit的函数,反之亦然,其中温度是用户输入并且转换已发布,下面是我希望获得帮助的代码

提前感谢任何可以提供帮助的人

<?php
function fahrenheit_to_celsius($temp)
{
    $celsius=5/9*($temp-32);
    return $celsius ;
}

function celsius_to_fahrenheit($temp)
{
    $fahrenheit=$temp*9/5+32;
    return $fahrenheit ;
}



?>

<!DOCTYPE html>
<html>
    <head>
        <title>Change Temperature</title>
        <style>
            #myForm {
    border: 1px solid grey;
    padding: 5px;   
    width: 600px;
}

.centered {
    width: 100%;
    text-align: center;
}


        </style>
    </head>
    <body>
    <div id="myForm">
        <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">


            <label for="temperature">Temperature:</label>
            <select id="temperature" name="temperature" class="myDropdown">
                <option value="">Please select a temperature...</option>
                <option value="C">celsius to fahrenheit</option>
                <option value="F">fahrenheit to celsius</option>
            </select>

            <br><br>



            <br><br>

            <?php
            if ($temperature==="C"){

                    echo celsius_to_fahrenheit($_POST[$celsius]);
                }


            if ($teperature==="F"){
                echo fahrenheit_to_celsius($_POST[$temp]);

            }

            ?>

            <label for="temp">Enter your temperature:</label>
            <input type="text" id="temp" name="temp">




            <div class="centered">
                <input type="submit" value="Submit temperature">
            </div>

        </form>
    </div>

    </body>
</html> 

1 个答案:

答案 0 :(得分:0)

这是有效的解决方法:

  <?php

$conversion = $_GET["conversion"];
echo $conversion;
$temp = $_GET["ForC"];
$celsius=5/9*($temp-32);
$fahrenheit=$temp*9/5+32;



$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");

$query = $dbh->query("select * from position"); // Run your query

echo '<form action="tempcfc.php" method="get">';

echo "conversion<br>";
echo '<select name="conversion">'; // Open your drop down box



// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}

echo '</select>';// Close your drop down box
echo "<br>";
echo "Type C or F<br>";
echo '<input type="text" name="ForC">';
echo "<br>";
echo "F<br>";
echo "<input type='text' name='F' value='" . $fahrenheit . "'>";
echo "<br>";
echo "C<br>";
echo "<input type='text' name='C' value='" . $celsius . "'>";
echo "<br>";
echo '<input type="submit" value="Submit">';

echo '</form>';

if ($conversion = "1") {
    $query = $dbh->query("insert into position (temp) values ('$fahrenheit')");
}
else {
    $query = $dbh->query("insert into position (temp) values ('$celsius')");
}


?>
相关问题