将变量传递到另一页时未定义的索引



我尝试使用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:XAMPPhtdocspage2.php 

您的数据没有被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>

我收回了那个评论。在您的表单中,您是导航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;
}
?> 
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>

在您的代码中,<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;
?>

所以您将得到空结果。

当你尝试像下面的一样提交表格时

<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

最新更新