2015-10-20 100 views
0

我有这个开关PHP开关不能正常工作

if(isset($_POST['submit'])) 

$type = $_POST['type']; 
{ 
     switch($type) 
     { 
      case 'm': 
       echo "Hello male"; 
       break; 
      case 'f': 
       echo "Hello female"; 
       break; 
      case 'c': 
       echo "Hello child"; 
       break; 
      default: 
       echo "you have to choose"; 
       break; 
     } 
} 

应该用这种形式的合作:

<form name="form" method="post" action=""> 
<p> 
    <input name="type" type="radio" value="f" />Woman 
    <br> 
    <input name="type" type="radio" value="m" />Male 
    <br> 
    <input name="type" type="radio" value="c" />Child 
    <br> 
    <input type="type" name="submit" value="Submit" /> 
</p> 
</form> 

但是当我测试了一下,在所有的情况下,不确定的变量返回。为什么是这样?

回答

5

简单的拼写错误:

变化:

if(isset($_POST['submit'])) 
$type = $_POST['type']; 
{ 

if(isset($_POST['submit'])) 
{ 
$type = $_POST['type']; 

你遗失了大括号。

因此,在POST之后执行的代码默认执行。

如果在任何表达式之后没有放置大括号,例如。 if,else,while,foreach,只有一行连续的代码将被执行。

因此,即使它们只包含一行代码,在这些控件之后添加大括号也是一种更好的做法。

+0

我猜我盯着自己在这一点盲目的,谢谢! – QueenOfRome

+0

现在,为什么默认返回这个错误: “注意:未定义的索引:键入[...]”? 参照这一行: '$ type = $ _POST ['type'];'' – QueenOfRome

2

使用此: PHP

if(isset($_POST['submit'])) 
{ $type = $_POST['type']; 
     switch($type) 
     { 
      case 'm': 
       echo "Hello male"; 
       break; 
      case 'f': 
       echo "Hello female"; 
       break; 
      case 'c': 
       echo "Hello child"; 
       break; 
      default: 
       echo "you have to choose"; 
       break; 
     } 
} 

HTML:

<form name="form" method="post" action=""> 
<p> 
    <input name="type" type="radio" value="f" />Woman 
    <br> 
    <input name="type" type="radio" value="m" />Male 
    <br> 
    <input name="type" type="radio" value="c" />Child 
    <br> 
    <input type="submit" name="submit" value="Submit" /> 
</p> 
</form> 
0

只是删除柯利括号后$_POST['type'];

必须是这样的:

$type = $_POST['type']; 
switch($type) 
{ 
    case 'm': 
     echo "Hello male"; 
     break; 
    case 'f': 
     echo "Hello female"; 
     break; 
    case 'c': 
     echo "Hello child"; 
     break; 
    default: 
     echo "you have to choose"; 
     break; 
} 
1

变化

<input type="type" name="submit" value="Submit" /> 

<input type="submit" name="submit" value="submit" /> 
      ^^^^^^      ^