dongyuan7981 2013-12-18 15:53
浏览 21

将多个数据插入MYSQL数据库

I am having problem inserting multiple data into MYSQL database. With the code below, I am only able to insert the data I have input. Let's say there are 3 questions and I must submit 3 inputs, it only submitted the last one.

 <?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
}
?>
  • 写回答

1条回答 默认 最新

  • dongmo9996 2013-12-18 16:05
    关注

    Few points: 1. your code is vulnerable to sql injection, use prepared data or SQLI/PDO 2. All your questions and answers are given the same name that's why you get only one inserted. Try giving them different names (using -1/-2/-3 sufix etc.), or if I make this, I would have 3 questions and 3 answers in the same record in database instead of inserting 3 times. 3. See below part. You need to add variables to both answer and id. Otherwise they are getting the same name.

        <input type=\"text\" name=\"answer\" class=\"answerField\">
    <input type="hidden" name="id" value="<?php echo $auctionRow    ['question_id'] ?>">
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制