【问题标题】:How to properly pass $_POST data to switch case statement using using filter_input_array如何使用 filter_input_array 正确地将 $_POST 数据传递给 switch case 语句
【发布时间】:2015-04-08 09:20:09
【问题描述】:

目标:映射/匹配到“postType”的 echo switch 语句案例

问题:无论我尝试什么,$_POST 数据似乎都消失了,因此触发了 switch 语句默认情况,并且表单再次显示,而不是我希望根据包含的 postType 显示的预期/期望的回显语句在 $filter 变量中。我正在使用 PHP 5.4

var_dump 返回: 数组(2) { ["postType"]=> NULL ["myContent"]=> 字符串(4) "dsfs" }

我相信我的表单和 switch 语句的语法/格式都是正确的。我的问题,我认为数据是如何通过 filter_input_array(INPUT_POST, [...]) 传递给交换机的

我不起眼的代码存根:

//test data
//$_POST = [ 'postType' => 'myPlayby',  'myContent' => 'Anna King', ];


//build the array of data created by from for switch checks
$filter = filter_input_array(INPUT_POST, [ 'postType'   => [], 'myContent'  => [], ]);


var_dump($filter);
echo "<br /><br />";


//$search = false;
switch ($filter['postType'])
{
case 'myChar':
    echo "Character Check: " . $filter['myCharacter'];
    $search = $filter['myCharacter'];
    break;

//test data ought to trigger myPlayby case showing 'Playby check: Anna King' here... frack
case 'myPlayby':
    echo "Playbe Check: " . $filter['myPlayby'];
    $search = $filter['myPlayby'];
    break;
case 'myFoobar':
    echo "Foo Check: " . $filter['myFooBar'];
    $search = $filter['myFooBar'];
    break;
default:
    echo '<form type="submit" method="post" action="' . THIS_PAGE . '"; >
        <select name="postTypes">
        <option default disable>-------------</option>
        <option value="myChar">Character</option>
        <option value="myPlayby">Playby</option>
        <option value="myFooBar">Foo</option>
        </select> 
        <input type="text" value="" name="myContent"/>
        <input type="submit" name="submit" value="Submit"> 
        </form>' ;
    break;
} 

这是我第一次使用 filter_input_array 处理 $_POST 数据,经过一天的试验、错误、研究和努力,包括查看 Lynda.com、搜索 Google 和阅读我可以在 StackOverflow 上找到的相关帖子, php.net等等,我很困惑。

【问题讨论】:

    标签: php forms post input switch-statement


    【解决方案1】:

    我找到了答案,我是正确的,问题在于我如何设置 filter_input_array。

    通过像这样重构代码:

    $filter = filter_input_array(INPUT_POST, [
      'postType'    => [ 'filter' => FILTER_SANITIZE_STRING ],
      'contents'    => [ 'filter' => FILTER_SANITIZE_STRING ],
    ]);
    
    $search = false; //in the switch, false is reassigned value of the sanitized string and all is happiness
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2020-09-01
      • 2011-08-15
      • 1970-01-01
      相关资源
      最近更新 更多