【问题标题】:Php Redirect to a new page from an if statement [duplicate]Php从if语句重定向到新页面[重复]
【发布时间】:2017-08-18 10:23:58
【问题描述】:

请专业的程序员在家里,这段代码有什么问题?

每当我尝试运行它时都会收到此错误。

解析错误:语法错误,意外';'在第 8 行的 C:\xampp\htdocs\a\go.php 中

php代码:

<?php

$term=$_POST['term'];
$level=$_POST['level'];

if  (

$term = 'First';
$level='js1';

)
{
header("Location: result.php");
exit();
} 
elseif (
$term = 'First';
$level='js2'; 
)
{
header("Location: result2.php");
exit();
} 

else {
$error = "Entry is invalid";
}

?>

【问题讨论】:

标签: php url redirect header


【解决方案1】:

检查你的 if 条件。 if 和 else if 条件不能包含任何分号。如果您使用两个比较,则必须使用 && 或 ||在他们之间。如果您在 if 和 elseif 语句中使用 =,那么它将始终返回 true。

<?php

$term=$_POST['term'];
$level=$_POST['level'];

if  ($term == 'First' && $level=='js1')
  {
    header("Location: result.php");
    exit();
  } 
else if ($term == 'First' && $level='js2')
  {
    header("Location: result2.php");
    exit();
  } 
else {
  $error = "Entry is invalid";
}

?>

【讨论】:

  • 太棒了!工作。谢谢
  • 除了解决这个烂摊子的好工作之外,还可以解释一下问题是什么以及如何解决它。
【解决方案2】:

改变你的 if 条件

应该是

if($term = 'First'&& $level='js1') or if($term = 'First'|| $level='js1') 

   elseif ($term = 'First' && $level='js2') or elseifif($term = 'First'|| $level='js2')

不是

if  ($term = 'First'; $level='js1';)

elseif ($term = 'First' ; $level='js2';)

【讨论】:

  • elseif 也是错误的。也许还值得一提
【解决方案3】:

您的所有if 语句格式错误。您所做的只是在if 语句中设置变量。因此,您没有正确使用赋值运算符。您的if 语句的外观示例如下:

if($condition === true || $condition2 == 'hello'){
    doSomething();
} else if($condition === false || $condtion2 == 'bye'){
    doSomethingElse();
}

编辑:另外,我建议您学习代码缩进技巧,这将有助于您将来阅读您的代码。

【讨论】:

  • 这是最好的答案。不仅仅是为提问者编写代码。但解释为什么它不起作用。
  • 感谢您的支持,我尝试始终使用give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime 理念。
【解决方案4】:

你没有在那些 if 中做出正确的布尔表达式。

if ($term === 'first' && $level === 'js1') {...}

elseif($term === 'First' && $level === 'js2') {...}

另外,我强烈建议您使用 die();重定向后避免不必要的负载(除非您需要在重定向后执行代码)。

【讨论】:

    【解决方案5】:

    试试这个。

    <?php
    
        $term=$_POST['term'];
        $level=$_POST['level'];
    
        if( $term == 'First' && $level=='js1'){
            header("Location: result.php");
            exit();
        } elseif ( $term == 'First' && $level=='js2'){
            header("Location: result2.php");
            exit();
        } else {
            $error = "Entry is invalid";
        }
    ?>
    

    【讨论】:

      【解决方案6】:

      如果您收到的标头已发送错误,则将 ob_start() 放在 php 文件的顶部,或者您也可以像下面这样使用 javascript。

      <script>window.location.href = "a.php";</script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 2023-01-12
        相关资源
        最近更新 更多