【问题标题】:Failure to display $result of a calculation未能显示 $result of a 计算
【发布时间】:2015-06-23 00:27:15
【问题描述】:

这里我们根据一个人选择的性别 ($gender) 和他们输入的身高 ($height) 计算一个人的理想体重 ($result)

由于某种原因,我无法从计算中看到回显的 $result。

有人知道为什么我看不到这个结果吗?

<?php
if(isset($_POST['Submit'])) {
$gender = $_POST['selectedGender'];
$height = $_POST['patientHeight'];
$result;
if ($gender == "Male") {
    $result = ($height * 4) - 128;
    echo $result; }           
else if ($gender == "Female") {    
    $result = ($height * 3.5) - 108;
    echo $result; }
}
?>
<html>
<div align="center">
<body>
<form name="form" method="post" action="<?php echo $PHP_SELF;?>">
    Select Your Gender: <select name="selectedGender">
        <option value=""></option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
    </select>
    <br><br>
    Enter Your Height: <input type="number" name="patientHeight" placeholder="Units are in Inches">
    <br><br>
    <input type="submit" name="Submit" value="Calculate Your Ideal Weight"/>
</form>
</body>
</div>
</html>

【问题讨论】:

  • name="patientheight"$_POST['patientHeight']。注意height/Heighth的情况?
  • @Sean 已编辑,谢谢!但是仍然无法显示 $result 。 :(
  • 您的代码看起来不错。您确定它没有在左上角回显$result,因为您在&lt;html&gt;&lt;body&gt; 标签之前有它吗?您可能希望在您的 body 中创建一个 div 来回显结果。
  • 虽然$PHP_SELF 应该是$_SERVER['PHP_SELF'] - stackoverflow.com/questions/12710803/…

标签: php


【解决方案1】:

您使用if / else if 并不是最好的方法。您应该使用switch/case 电话。

switch($gender) {
    case "Male":
    $result = ($height * 4) - 128;
    break;
    case "Female":
    $result = ($height * 3.5) - 108;
    break;
    default:                         // notice the 'default' here?
    $result = 'derp';                // that will set it always.
    break;                           // meaning if you don't have a value present.
}
echo $result;

以上将涵盖所有结果,包括未设置$gender 的结果。

如其他答案所述,没有名为$PHP_SELF 的变量,您会在服务器超级全局 - $_SERVER['PHP_SELF'] 中找到它。

【讨论】:

    【解决方案2】:

    我注意到有一个名为 selectedGender 的空单选按钮。如果将 this 传递给表单,则 if else if 语句将不会捕获它,并且不会回显任何内容。

    也许去掉那个空的单选按钮,或者添加一个最后的else 声明。

    【讨论】:

      【解决方案3】:

      您的回声高于&lt;html&gt;。此代码将计算权重并将其呈现在 javascript 警报中:

      <?php
      if(isset($_POST['Submit'])) {
      $gender = $_POST['selectedGender'];
      $height = $_POST['patientHeight'];
      $result;
      if ($gender == "Male") { $result = ($height * 4) - 128; }           
      else if ($gender == "Female") { $result = ($height * 3.5) - 108; }
      
          $msg = 'As a '.$gender.' '.$height.' inches tall your weight should be '.$result.' pounds.';
          echo '<Script language="javascript">alert("'.$msg.'");"</script>';
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        • 1970-01-01
        • 2014-09-22
        • 2018-07-18
        • 1970-01-01
        • 2018-08-17
        相关资源
        最近更新 更多