php - 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?
提前致谢!
解决方案
您应该对元素执行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));
推荐阅读
- python - 如何找到列表中键最多的字典?
- docusignapi - 检查 HMAC 签名
- c# - 使用带有 sql 查询的文本框过滤 WPF C# DataGrid
- kubernetes - 在 Operator-SDK 中,多个 Patch 在一个协调功能中
- jquery - Moodle 测验仅在尝试期间而不是在复习期间显示模式
- java - 为什么 SonarQube 添加“没有足够的论点”。对于带有消息和 Throwable 的日志方法?
- android - 使用 Koin 进行适当的仪器测试
- python-3.x - 如何使用 elasticsearch-dsl-py 加入两个 ElasticSearch 索引?
- windows - 无法在 windows server 2019 节点上创建 kubernetes pod
- core-data - 如何在 coreData 的谓词中使用 AppStorage