将变量传递给另一个页面时的未定义索引

时间:2014-04-13 11:35:23

标签: php variables

我尝试使用post将我的变量q2传递给不同的页面,但它不断得到未定义的索引错误。 这是我的代码: 第1页:

<form action="page2.php" method="post">
Question 2: Your age ?<br> <input type = "radio" name="q2" value="a"> 15-<br>
<input type = "radio" name="q2" value ="b"> 15-25<br>
<input type = "radio" name="q2" value ="c"> 25-35<br>
<input type = "radio" name="q2" value ="d"> 35+<br>
</form>
<a href="page2.php">Submit</a>

第2页:

<?php
$q2 = $_POST['q2'];
Echo $q2;
?>

第2页输出:

Notice: Undefined index: q2 in D:\XAMPP\htdocs\page2.php 

4 个答案:

答案 0 :(得分:2)

您的数据未被POST,因为您只是链接到page2.php。

需要改为

<form action="page2.php" method="post">
Question 2: Your age ?<br> <input type = "radio" name="q2" value="a"> 15-<br>
<input type = "radio" name="q2" value ="b"> 15-25<br>
<input type = "radio" name="q2" value ="c"> 25-35<br>
<input type = "radio" name="q2" value ="d"> 35+<br>
<input type='submit' value='Submit' />
</form>

答案 1 :(得分:0)

我接受了这个评论。在您的表单中,您导航page2.php,而非提交表单。

正确的方法是:

<input type = "radio" name="q2" value ="d"> 35+<br>
<!-- add the submit button inside the form -->
<input type="submit" name="submit"> 
</form> 

在您的page2.php

<?php
//always use isset before checking for POST variables
if(isset($_POST['submit']){
  $q2 = $_POST['q2'];
  echo $q2;
}
?> 

答案 2 :(得分:0)

You have already written in form action 

no need of this <a href="page2.php">Submit</a>

<input type="button" id="submit" name="submit" value="Submit"/>
write this line before </form> tag close instead of this line 
<a href="page2.php">Submit</a>

答案 3 :(得分:0)

在您的代码<a href="page2.php">Submit</a>中只是一个链接。这不是表格提交。

<form action="page2.php" method="post">
Question 2: Your age ?<br> 
<input type = "radio" name="q2" value="a"> 15-<br>
<input type = "radio" name="q2" value ="b"> 15-25<br>
<input type = "radio" name="q2" value ="c"> 25-35<br>
<input type = "radio" name="q2" value ="d"> 35+<br>
</form>
<a href="page2.php">Submit</a>

在page.php中,您可以使用var_dump进行调试。类似于以下内容

<?php
$q2 = $_POST['q2'];
var_dump($q2);
echo $q2;
?>

所以你会得到null结果。

当您尝试使用表单提交时,如下所示

<form action="page2.php" method="post">
Question 2: Your age ?<br> 
<input type = "radio" name="q2" value="a"> 15-<br>
<input type = "radio" name="q2" value ="b"> 15-25<br>
<input type = "radio" name="q2" value ="c"> 25-35<br>
<input type = "radio" name="q2" value ="d"> 35+<br>
<input type='submit' value='Submit' />
</form>

您将获得类似

的内容

string(1) "a" a string(1) "b" b string(1) "c" c string(1) "d" d