1
<?PHP
session_start();
if (isset($_SESSION['hasVoted']) && $_SESSION['hasVoted'] == '1') {
        print "You've already voted";
    }
else {
    if (isset($_POST['Submit1'])) {
        $ID = $_SESSION['user']; // obtain the ID of the user from the login session
        var_dump($ID);
        $string_results = $_POST['h2'];
        $selected_radio = explode(',', $string_results);
        var_dump($selected_radio);
        $user_name = "root";
        $password = "";
        $database = "surveyTest";
        $server = "127.0.0.1";
        $SQL = "SELECT * FROM tblquestions";
        $db_handle = mysql_connect($server, $user_name, $password);
        $db_found = mysql_select_db($database, $db_handle);
        if ($db_found) {
            $result = mysql_query($SQL);
            $numRows = mysql_num_rows($result); //return number of rows in the table
            var_dump($numRows);
            $qNum = 'q1';
            for ($i = 0; $i < $numRows; $i++)
            {
                var_dump($qNum);
                $_SESSION['hasVoted'] = '1';
                $selected_Value = $selected_radio[$i];
                var_dump($selected_Value);
            //==================================================================================
            //  SET Multiple rows IN THE answers TABLE for each question for a given student.
            //==================================================================================
                $SQL = "INSERT INTO answers (QID, Answer, SID) VALUES ('$qNum', '$selected_Value', '$ID')";
                $result = mysql_query($SQL);
                    $question_Number = ltrim($qNum,'q');
                    $question_Number++;
                    $qNum ='q'.$question_Number;
            }
                mysql_close($db_handle);
                print "Thank you for participating!";
        }
        else {
        print "database error";
        }
    }

    else {
        header("location:login.php");;
    }
}
session_destroy();
?>

<html>
<head>
<title>Process Survey</title>
</head>



<body>

</body>
</html>

当我执行上述代码时,包含 INSERT 的 $SQL 语句只执行一次。这意味着它只向数据库添加一条记录。但是,我需要它向数据库中添加几条等于 $numRows 的记录。$qNum 和 $selected_Value 的打印结果显示正确。有什么建议么?

4

2 回答 2

2

再试一次$result = mysql_query($SQL) or die(mysql_error());

您的桌子上的主键也可以吗?

于 2013-07-09T20:23:00.493 回答
0

为了使您的代码正常工作,您的变量中必须有相同的数字$numRows,这取决于您的$result变量,就像您在 中所做的那样count($selected_radio),可能并非如此。我还担心您可能没有 HTML <input type='radio' value='whatever' name='h2' />。为什么这是一个逗号分隔的字符串?单选按钮应该只返回值为'checked'. 无论如何,也许你有name='h2',在一个隐藏的输入或什么的。在这种情况下,您的循环应该类似于:

for($i=0,$l=count($selected_radio); $i<$l; $i++){
  //your code in here
}

如果我是你,我会使用PHPglue 之类的库来处理你的 Sticky Form 问题。访问https://www.PHPglue.com了解更多详情。

于 2013-07-09T20:51:06.030 回答