如何使用动态单选按钮从表单中将数据插入到数据库中?

时间:2016-02-10 05:49:04

标签: php mysql forms

我正在尝试使用动态生成的单选按钮从表单中插入数据用于测验页面。我无法访问由表单发布的数据,其名称为array.Please帮助我这样做。如果您发现任何错误,它必须是大帮助.Thankyou

        <?php
        $rs=mysql_query("select * from question where testid=$tid order by quesid ",$cn) or die(mysql_error()); 
        $n=0;
        while($row= mysql_fetch_row($rs)){?>
        <form name=myfm method=post action=Quiz.php>
        <table width=100%> <tr> <td width=30><td></td></td></tr> <table border=0>
        <?php $n=$n+1; ?>
        <tr><td>Question  <?php echo $n." "; echo $row[2]; ?></td></tr>
        <tr><td class=style8><input type="radio" name="ques['<?php echo $n; ?>'][]" value=1><?php echo $row[3]; ?></td></tr>
        <tr><td class=style8> <input type="radio" name="ques['<?php echo $n; ?>'][]" value=2><?php echo $row[4];?></td></tr>
        <tr><td class=style8><input type="radio" name="ques['<?php echo $n; ?>'][]"  value=3><?php echo $row[5];?></td></tr>
        <tr><td class=style8><input type="radio" name="ques['<?php echo $n; ?>'][]"  value=4><?php echo $row[6];?></td></tr>

    <?php 
        }
        echo "<tr><td><input type=submit name=submit id='result' value='Get Result'></form>";
        ?>
        </table></table>
        </form>

数据插入页面

        <?php 
        $rs=mysql_query("select * from question where testid=$tid",$cn) or die(mysql_error());
        if($submit=='Get Result')
        { $n=0;
        while($row= mysql_fetch_row($rs)){
        for($i=0;$i<count($_POST['ques']);$i++)
        {$n=$n+1;
        $ans=$_POST['ques'][$n][$i];
        mysql_query("insert into useranswer(sessid, testid, ques, ans1,ans2,ans3,ans4,correctans,yourans) values ('".session_id()."',       $tid,'$row[2]','$row[3]','$row[4]','$row[5]', '$row[6]','$row[7]','$ans')") or die(mysql_error());
        }
        ?>

1 个答案:

答案 0 :(得分:1)

您有一个变量$tid。那应该是这样的。

$rs=mysql_query("select * from question where testid=".$tid,$cn)

不要忘记在查询中添加mysql_real_escape_string

  

mysql_real_escape_string - 转义字符串中的特殊字符以便在SQL语句中使用。但是在PHP中不推荐使用此扩展名   5.5.0,它已在PHP 7.0.0中删除。相反,应该使用MySQLi或PDO_MySQL扩展。

更新:::

  

mysql_real_escape_string

 // We have not connected to MySQL

 $lastname  = "O'Reilly";
 $_lastname = mysql_real_escape_string($lastname);

 $query = "SELECT * FROM actors WHERE last_name = '$_lastname'";

更新2 ::

$tid = mysql_real_escape_string($tid);
$ans = mysql_real_escape_string($ans);

mysql_query("insert into useranswer(sessid, testid, ques, ans1,ans2,ans3,ans4,correctans,yourans) values ('".session_id()."',       '". $tid ."','$row[2]','$row[3]','$row[4]','$row[5]', '$row[6]','$row[7]','". $ans .'")") or die(mysql_error());