PHP IF / ELSEIF / ELSE 不起作用



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

网页代码:

<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> 

更新GCcads.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);
?>

因此,我通过将"elseif"更改为"else if"来使其工作。我不确定为什么会这样,PHP文档也不清楚,所以如果有人能对此有所了解,我将不胜感激。谢谢!

您可能需要考虑以下代码。差别不大,但可能允许增长。

<?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()。发人深思的东西。

最新更新