0

我有一个我一直在做的小项目。我必须使用一个文件或 PHP_SELF 创建一个面积转换计算器。我遇到的问题是表单正在工作并输出数字,但无论我选择哪种转换方法,它都只会输出最后一个 if 语句。它将始终输出 Sq.Miles。

if (!empty($_POST['con'])) {
    $con = $_POST['con'];
} else {
    $error .= "You need to select a conversion Method. <br>";
}
if (!empty($_POST['number'])) {
    $num = $_POST['number'];
    } else {
    $error .= "You need to type in a number. <br>";
} 
if (empty($error)) {
    if ($con = "SFSM") {
        $result = $num * 0.093 . " Sq. Meters";
    }
    if ($con = "SYSM") {
        $result = $num * 0.84 . " Sq. Meters";
    }
    if ($con = "SMSK") {
        $result = $num * 2.6 . " Sq. Kiometers";
    }
    if ($con = "SMSF") {
        $result = $num * 10.76 . " Sq. Feet";
    }
    if ($con = "SMSY") {
        $result = $num * 1.2 . " Sq. Yards";
    }
    if ($con = "SKSM") {
        $result = $num * 0.38 . " Sq. Miles";
    }
}
}
?>
<form method="post" action="area2.php">
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2">Area Conversions</td>
</tr>
<tr>
<td>Conversion Method</td>
<td>Number</td>
</tr>
<tr>
<td>
<select name="con">
 <option selected="selected" style="color:#CCC"></option>
 <option value="SFSM">Square Feet to Square Meters</option>
 <option value="SYSM">Square Yards to Square Meters</option>
 <option value="SMSK">Square Miles to Square Kilometers</option>
 <option value="SMSF">Square Meters to Square Feet</option>
 <option value="SMSY">Square Meters to Square Yards</option>
 <option value="SKSM">Square Kilometers to Square Miles</option>
 </select>
 </td>
 <td>
  <input type="text" name="number" size="10" value = "<?php if ($num){ echo $num; } else           {           echo "Insert Number"; } ?>" onfocus="this.value==this.defaultValue?this.value='':null"/><br />
  </td>
  </tr>
  <tr>
  <td colspan="2">
       <input type="submit" value="Calculate" name="submit" />
       <input type="reset" value="reset" name="reset" />
</td>
</tr>
<?php
if (!empty($error)) {
echo $error;
}elseif (!empty($result)) {
echo "<tr><td colspan=\"2\">Result: " . $result . " </td></tr>";
}
?>
</table>
</form>
4

1 回答 1

6

尝试:

if ($con == "SFSM") {

=运算符是赋值;==是比较。

本质上,您的 if 语句都评估为 true;并且由于他们都设置了变量,因此它只是实际出现的最后一个调用

于 2012-07-10T18:03:42.310 回答