我在将多个数据插入MYSQL数据库时遇到问题。使用下面的代码,我只能插入我输入的数据。假设有3个问题,我必须提交3个输入,它只提交最后一个。
<?php
include('questionDB.php');
if(isset($_POST['submit'])){
$questionID = $_POST['id'];
$answer = mysql_real_escape_string(htmlspecialchars($_POST['answer']));
$insert = mysql_query("INSERT INTO answers(survey_id, question_id, answer_body) VALUES ('1','" . $questionID . "', '" . $answer . "')");
if ($insert){
echo "Success";
} else {
echo "Failed";
}
}
$startTimeAuc = mysql_query("SELECT startTime FROM questions WHERE survey_id='1'");
$startTime = mysql_fetch_assoc($startTimeAuc);
$startTime = ($startTime['startTime']);
$endTimeAuc = mysql_query("SELECT endTime FROM questions WHERE survey_id='1'");
$endTime = mysql_fetch_assoc($endTimeAuc);
$endTime = ($endTime['endTime']);
$currentTimeAuc =(date("Y-m-d H:i:s"));
if( ( $currentTimeAuc >= $startTime && $currentTimeAuc <= $endTime)){
?>
<form name="auctionQuestion" method="post">
<?php
$auctionSurvey = "SELECT question_id, survey_id, question_body FROM questions
WHERE survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while($auctionRow = mysql_fetch_assoc($aucResult)){
echo "<p class=\"questions\">". $auctionRow['question_body']."</p>". "<input type=\"text\" name=\"answer\" class=\"answerField\"><BR>";
?>
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">
<?php
}
?>
<input type="submit" class="submit" name="submit" value="Submit">
</form>
</div>
<?php
}
?>
答案 0 :(得分:0)
几点: 1.你的代码容易受到sql注入,使用准备好的数据或SQLI / PDO 2.您的所有问题和答案都与您只插入一个问题的名称相同。尝试给他们不同的名字(使用-1 / -2 / -3 sufix等),或者如果我这样做,我将在数据库中的同一记录中有3个问题和3个答案,而不是插入3次。 3.见下文部分。您需要为answer和id添加变量。否则他们会得到相同的名字。
<input type=\"text\" name=\"answer\" class=\"answerField\">
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">