<?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的打印显示正确的事情。有什么建议吗?
答案 0 :(得分:2)
使用$result = mysql_query($SQL) or die(mysql_error());
桌子上的主键也可以吗?
答案 1 :(得分: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 这样的库来处理你的粘性表格问题。请访问https://www.PHPglue.com了解详情。