我是php新手,作为测试,我构建了一个测试应用程序,它可以加载存储在数据库中的问题,并将它们显示在一个带有输入类型单选按钮的表中,供用户选择答案。有四个表。问题,答案,用户,userexam。每个表中的行包含一个id作为索引。我遇到的麻烦是在点击提交按钮时将值输入数据库。我将如何循环并将每个问题值添加到数据库中,而无需单独定义每个ID?
<?php
$getQuestions = "
SELECT
*
FROM
questions
WHERE questions.active = '1'
ORDER BY
questionID
";
$qResult = mysql_query($getQuestions);
$tableString = "<table>
<tr>
<th>
Questions
</th>
<th>
Answers
</th>
</tr>";
while ($qRow = mysql_fetch_assoc($qResult)) {
$getAnswers = "
SELECT
*
FROM
answers a
WHERE
a.questionID = '" . $qRow['questionID'] . "'
ORDER BY
a.questionID,
a.answerNumber
";
$aResult = mysql_query($getAnswers);
$tableString .= "<tr>
<td>" .
$qRow['question'] .
"</td>
<td>";
while ($aRow = mysql_fetch_assoc($aResult)) {
if ($aRow['correct'] == 1) {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
} else {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
}
$answer=$_POST['. $aRow["answerID"] .'];
$question=$_POST['. $qRow["questionID"] .'];
$student=$_POST['userID'];
// Insert data into mysql
$sql="INSERT INTO $userexam(answerID, questionID, userID)VALUES('$answer', '$question', '$student')";
$result=mysql_query($sql);
}
}
$tableString .= "</table>";
echo $tableString;
?>
答案 0 :(得分:0)
在mysql的每个地方使用mysqli(mysql-improved)。
<?php
//Set database conection
$conection=mysqli_connect('localhost','root','','Your database name');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$getQuestions = "
SELECT
*
FROM
questions
WHERE questions.active = '1'
ORDER BY
questionID
";
$qResult = mysqli_query($conection,$getQuestions);
$tableString = "<table>
<tr>
<th>
Questions
</th>
<th>
Answers
</th>
</tr>";
while ($qRow = mysqli_fetch_assoc($qResult)) {
$getAnswers = "
SELECT
*
FROM
answers a
WHERE
a.questionID = '" . $qRow['questionID'] . "'
ORDER BY
a.questionID,
a.answerNumber
";
$aResult = mysqli_query($conection,$getAnswers);
$tableString .= "<tr>
<td>" .
$qRow['question'] .
"</td>
<td>";
while ($aRow = mysqli_fetch_assoc($aResult)) {
if ($aRow['correct'] == 1) {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
} else {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
}
$answer=$_POST['. $aRow["answerID"] .'];
$question=$_POST['. $qRow["questionID"] .'];
$student=$_POST['userID'];
// Insert data into mysql
$sql="INSERT INTO userexam(answerID, questionID, userID)VALUES('$answer', '$question', '$student')";
$result=mysqli_query($conection,$sql);
}
}
$tableString .= "</table>";
echo $tableString;
mysqli_close($conection);
?>