首页 > 解决方案 > PHP:$_POST 无法检索现有输入

问题描述

我正在尝试制作一个按钮,根据页面上选择的表单/输入,将您带到一个名为“typeDefine.php?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism”的页面=1"(数字因所选输入而异)。但是,$selectedNum(理想情况下包含每个输入的 $_POST 的变量)会在页面加载后立即返回错误,说明:

未定义的索引

<?php
                
    $typeWords = array("openness", "conscientiousness", "extroversion", "agreeableness", "neuroticism");
    $typeLetters = array("o", "c", "e", "a", "n");
    $typePath = "";
    $correspondingLetters = array("I", "II", "III");

    $isFirst = true;
                
    foreach($typeWords as $typeWord)
    {
        $selectedNum = $_POST[$typeWord];//error here!!!
                    
        if(isset($selectedNum))//if got $typeWord in a form
        {
            $separationChar;
                        
            if($isFirst)
            {
                $separationChar = "?";
                
                $isFirst = false;
            }
            else
            {
                $separationChar = "&";
            }

            $typePath = $typePath . $separationChar . $typeWord . "=" . $selectedNum;//e.g. $typePath = "?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1" for $_GET method after arriving on next page
        }
    }
                
    echo '<a href = "typeDefine.php' . $typePath . '" class = "button" style = "font-size: 400%; padding: 3.85rem 0;">search for type</a>
                
    <div>';
                    
        foreach($typeWords as $typeWord)
        {
            $typeLetter = substr($typeWord, 0, 1);
                        
            echo '<form method = "post" class = "column">';
                        
                for($i = 1; $i <= 3; $i++)
                {
                    echo '<input type = "radio" name = "' . $typeWord . '" id = "' . $typeLetter . $i . '"><label for = "' . $typeLetter . $i . '">' . $correspondingLetters[$i - 1] . '</label>';//sets each input name to $typeWord for $_POST above
                }
                            
                echo '<li class = "textHighlight">' . $typeWord . '</li>
                            
            </form>';
        }
                    
    echo '</div>';
            
?>

我可以做些什么来解决这个错误,然后填充 $typePath 并使脚本在单击按钮时正确地将您带到所需的 url?

为了便于理解,这里是页面截图

提前致谢!

标签: phphtml

解决方案


您应该对元素执行isset()测试$_POST,而不是您从中设置的变量。

    foreach ($typeWords as $typeWord)
    {
        if (isset($_POST[$typeWord])) {
            $selectedNum = $_POST[$typeWord];
            $typePath = $typePath . "?" . $typeWord . "=" . $selectedNum;
        }
    }

请注意,多个参数需要用 , 分隔&?只能在开头使用。有一个内置函数可以从数组创建查询字符串,您可以使用它:

    $typeArray = [];
    foreach ($typeWords as $typeWord)
    {
        if (isset($_POST[$typeWord])) {
            $selectedNum = $_POST[$typeWord];
            $typeArray[$typeWord] = $selectedNum;
        }
    }
    $typePath = $typePath . "?" . http_build_query($typeArray);

您还可以将循环替换为:

$typeArray = array_intersect_key($_POST, array_flip($typeWords));

推荐阅读