【问题标题】:PHP IF / ELSEIF / ELSE NOT WORKINGPHP IF / ELSEIF / ELSE 不工作
【发布时间】:2018-08-22 07:10:55
【问题描述】:

我有一个 PHP 脚本,它接受从 HTML 表单传递的变量并更新一个平面文件。问题是简单的 if / elseif / else 语句不起作用,具体来说,它在执行比较时没有打开正确的文件。表单的输入将始终写入最后一个文件,即 gcads3.txt。我已经测试过正确的细节从表单传递到脚本,即一个、两个或三个正确地传递给 $col,所以我知道这是错误的比较。我已经根据 PHP 文档和有关此问题的其他帖子检查了 if / elseif / else 语法,请问我错过了什么?先感谢您。

HTML 代码:

<form action="updategcads.php" method="post" enctype="multipart/form-data">
  <p>Enter the column to add the new line to:</p>
  <p><input type="radio" name="col" value="one"/> Column 1 
     &nbsp;&nbsp;
     <input type="radio" name="col" value="two"/> Column 2 
     &nbsp;&nbsp;
     <input type="radio" name="col" value="three"/> Column 3
  </p>
  <p>Enter the new line to add:<br><span>(enter the name)</span></p>
  <p><input type="text" name="advs" size="50"/></p>
  <p><input type="submit" value="Update"/></p>
</form> 

更新gcads.php代码:

<?php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{
  $col = $_POST["col"]; 
  $line = $_POST["advs"]; 
}

if ($col=="one")
{
  $file = fopen("../gcads1.txt", "a") or die("unable to open $file: $!");
} 
elseif ($col=="two") 
{
  $file = fopen("../gcads2.txt", "a") or die("unable to open $file: $!");
} 
else
{
  $file = fopen("../gcads3.txt", "a") or die("unable to open $file: $!");
}

fwrite($file, $line);
fclose($file);
?>

【问题讨论】:

  • php中使用strcmp比较字符串
  • 您应该尝试记录您的比较结果之一。你会发现这并不完全合理。完成后,我建议您检查 === 和 == 之间的区别。最后检查 strcomp() 函数必须提供什么。
  • 旁注,您不需要为此使用 post,也不需要此表单是多类型/表单数据。您应该将整个比较部分包含在 isset 检查中,并尝试检查已知值。 isset($_POST['col']) - 因为 $_POST 总是被设置。
  • @Ali - 一定会调查一下,谢谢。
  • @kashalo - 非常有帮助,谢谢。

标签: php forms


【解决方案1】:

所以,我通过将“elseif”更改为“else if”来实现这一点。我不确定为什么会这样,而且 PHP 文档也不清楚,所以如果有人能对此有所了解,我将不胜感激。谢谢!

【讨论】:

  • 我认为twisty总结了上面的内容。它可能是 php 版本,但老实说,它从来没有为我做过,所以我不肯定为什么它会适合你。关于 GET/POST 的使用存在一些意见,但表单处理中的读/写协议的概念更像是传统习惯,而不是正确的编码。如果你的接收脚本做得好,到头来也没多大关系。
【解决方案2】:

您可能需要考虑以下代码。没有太大的不同,但可能会允许增长。

<?php
if(isset($_POST['col']) {
  $col = $_POST["col"]; 
  $line = $_POST["advs"]; 
}
$nums = array(
  "one" => 1,
  "two" => 2,
  "three" => 3,
  "four" => 4,
  "five" => 5.
  "six" => 6,
  "seven" => 7,
  "eight" => 8,
  "nine" => 9,
  "zero" => 0
);

$file = fopen("../gcads" . $nums[$col] . ".txt", "a") or die("unable to open $file: $!");

fwrite($file, $line);
fclose($file);
?>

或者,您也可以使用switch()。值得深思。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多