html表单名称= php变量

时间:2011-09-22 06:35:11

标签: php html forms

我有一个用户必须填写的表单(基本上是一个测试)。我从MySQL表中得到的问题但我无法将问题编号转移到answer.php文件中。

形式

$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1))
{
    $test_name=$row1['test_name'];
    $q_nr=$row1['q_nr'];
    $q_type=$row1['q_type'];
    $question=$row1['question'];
    $option1=$row1['option1'];
    $option2=$row1['option2'];
    echo "<form method='post' action='answer.php'>";
    echo "<P><strong>$q_nr $question</strong><BR>";
    echo "<input type='radio' name='$q_nr' value='option1'>$option1<BR>";
    echo "<input type='radio' name='$q_nr' value='option2'>$option2<BR>";
    echo "<BR>";
    echo "<BR>";
    echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";
?>

answer.php

<?php
$q_nr = $_GET['q_nr'] ;
echo $q_nr;
?>

3 个答案:

答案 0 :(得分:1)

首先,您的表单提交方法是POST,您正在GET中检索

其次它不会起作用,你在循环中创建了许多表单,这是一个逻辑上存在的问题,把你的FORM放在循环之外,让elelent成为一个像q_nr [] -------的数组

答案 1 :(得分:0)

如果FORM METHOD等于POST,你会得到$ _POST超全局变量中的参数:

 $q_nr = $_POST['q_nr'] ;

答案 2 :(得分:0)

我假设您想要获取所有问题并在一页上显示,然后将所有答案提交给answer.php?在这种情况下,您可以:

$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);

echo "<form method='post' action='answer.php'>";

while($row1 = mysql_fetch_array($result1))
{
    $test_name=$row1['test_name'];
    $q_nr=$row1['q_nr'];
    $q_type=$row1['q_type'];
    $question=$row1['question'];
    $option1=$row1['option1'];
    $option2=$row1['option2'];

    echo "<P><strong>$q_nr $question</strong><BR>";
    echo "<input type='radio' name='question[$q_nr]' value='$option1'>$option1<BR>";
    echo "<input type='radio' name='question[$q_nr]' value='$option2'>$option2<BR>";
    echo "<BR>";
    echo "<BR>";
    echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";

关于answer.php:

//Key is $q_nr and $answer is selected $option
foreach($_POST['question'] as $key => $answer) {
    echo $key;
}