PHP 中的开关语句


Switch statement in PHP

我正在尝试进行一些错误检查。 我想这样做,如果 html 页面上没有选中单选按钮,它将传递给 php 并告诉用户选择一个单选按钮和一个链接以返回该页面。

包括我当前的代码:

.PHP

<?php

switch($_POST["city"]){
    case "sf":
        echo "Welcome to San Francisco, enjoy the beautiful weather.";
        break;
    case "tokyo":
        echo "Welcome to Tokyo, enjoy the sushi.";
        break;
    case "paris";
        echo "Welcome to Paris, enjoy the Eiffel Tower.";
        break;
    Default:
        echo "Please pick a city.";
        echo "<a href='"/week7.html'">Go Back</a>";

}
?>

.HTML

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
            <form action="Week7PHP.php" method="post">
                <input type="radio" name="city" value="sf">San Francisco<br />
                <input type="radio" name="city" value="paris">Paris<br/>
                <input type="radio" name="city" value="tokyo">Tokyo<br/>
                <input type="submit" id="Submit">
            </form>
        </div>
    </body>
</html>

当它找不到任何选中的单选按钮时,它会给出错误。

如果未选择任何选项,则会出现此错误:注意:未定义索引:城市

您需要

default:选项后添加一个break;。而且你在"paris"之后有一个放错位置的分号,它应该是一个冒号。

<?php

switch($_POST["city"]){
    case "sf":
        echo "Welcome to San Francisco, enjoy the beautiful weather.";
        break;
    case "tokyo":
        echo "Welcome to Tokyo, enjoy the sushi.";
        break;
    case "paris":
        echo "Welcome to Paris, enjoy the Eiffel Tower.";
        break;
    default:
        echo "Please pick a city.";
        echo "<a href='"/week7.html'">Go Back</a>";
        break;
}
?>

问题是 switch 语句在没有设置的情况下尝试访问$_POST["city"]。这是isset()功能的完美用法:

if (isset($_POST["city")) {
   /* switch statement */
} else {
   /* form element*/
}

您可能收到错误的原因是您在通过发布设置

之前使用$_POST["city"]

我个人不会在交换机中使用_POST _GET _REQUEST全局变量。无论检查和处理这些"特殊"变量的脚本多么基本,我都会编写一个控制器。

简单如下:

<?php 
if(isset($_POST['city'])){
    $city=$_POST['city'];
}else{
    $city='';
}
//Or simpler
$city=(isset($_POST['city']))?$_POST['city']:'';

//The use $city
switch($city){
    case "sf":
        echo "Welcome to San Francisco, enjoy the beautiful weather.";
        break;
    case "tokyo":
        echo "Welcome to Tokyo, enjoy the sushi.";
        break;
    ...
    ...
?>