Php 检查是否使用POST检查radiobutton
我正试图将用户重定向到另一个网页,具体取决于他们选中的单选按钮 以下是相关代码:Php 检查是否使用POST检查radiobutton,php,html,forms,radio-button,Php,Html,Forms,Radio Button,我正试图将用户重定向到另一个网页,具体取决于他们选中的单选按钮 以下是相关代码: <form action="sample.php" method="post"> <input name="survey" type="radio" value="Yes" /> Yes </br> <input name="survey" type="radio" value="No" /> No
<form action="sample.php" method="post">
<input name="survey" type="radio" value="Yes" /> Yes
</br>
<input name="survey" type="radio" value="No" /> No
</form>
<?
if ($_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if ($_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
?>
对
不
由于某种原因,我的if语句中出现了一个错误。无法将“调查”识别为有效索引。我怎么会无法将表单链接到php代码?您的警告是因为当您使用
GET
(正常请求)加载页面时,$\u POST['survey']
未设置
您可以通过在每次使用前添加isset($\u POST['survey'])&&
来更改您的条件,或者您可以将整个代码放在一个块中,以检查帖子是否制作为:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if ($_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if ($_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
}
else
{
// output html
}
无论哪种方式,您都必须将其放在html前面,因为如果标题已发送(内容已输出到浏览器),则无法使用
标题。想想表单的工作方式:
第一次访问页面时,表单未提交。然而,您的if/else
的行为就好像是这样。这就是导致错误的原因-$\u POST['survey']
第一次不存在
正确编写脚本-在呈现HTML之前执行所有可能的表单处理:
<?php
if (isset($_POST['submit'])) {
// handle the form
}
?>
<!doctype html>
<html>
<head>
<title>Blah</title>
</head>
<body>
<!-- code -->
</body>
</html>
废话
这将允许您检查表单是否已提交给自身,并可能使用header()
重定向用户,而不会遇到令人讨厌的“Headers ready sent”错误。尝试一个简单的print\r()语句,查看$\u POST是否有任何内容。将此内容放在页面顶部:
print_r($_POST);
另外,请确保您正在通过表单加载结果页面。如果您只是键入页面的URL,它将不会发送任何POST数据。第一次加载文件sample.php时,没有POST数据,因此没有索引“survey”
您需要将其嵌套在另一个if语句中,或按以下方式对其进行修改:
<form action="sample.php" method="post">
<input name="survey" type="radio" value="Yes" /> Yes
</br>
<input name="survey" type="radio" value="No" /> No
</form>
<?
if (isset($_POST) && $_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if (isset($_POST) && $_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
?>
对
不
我正在使用不同的php文件进行检查
<html>
<body>
<form action="another.php" method="POST">
<label>You are: </label> Male <input type="radio" name="male"> Female <input type="radio" name="female"><br/><br/>
<input type="submit" name="submit" value="GO">
</body>
</html>
你是:男性女性
*****另一个.php******
<?php
if (isset($_POST['submit']))
{
if(empty($_POST['male']) && empty($_POST['female']))
{echo "select gender";}
elseif (empty($_POST['female'])) //means Male is checked
{
$gend="Male";
echo $gend;
}
elseif(empty($_POST['male'])) //Means Female is checked
{
$gend="Female";
echo $gend;
}
elseif(empty($_POST['male']) || empty($_POST['female'])== false) //Not required if you can disable one when another is checked
{echo"please select only one";}
}
?>
是一个文档还是两个单独的文件?此代码位于单个文件中。但是重定向到了另一个文件。我不知道你的意思是什么?我正在使用单选按钮?关于如何构造代码的更多信息:长话短说,在PHP和HTML之间来回跳跃只会让人落泪。不要这样做。相反,请提前完成所有PHP工作,然后显示结果。谢谢。你把概念解释得很好。我是编程新手,这对我很有帮助。