多次插入数据库无法正常工作

时间:2018-02-27 16:59:32

标签: php database insert multiple-insert

我试图一次在我的数据库中插入多行。

用户可以添加最多5个新行,以便将血液结果插入到数据库中。

有一个添加更多按钮,允许他们这样做。

我有一个循环遍历每个条目,但是当我点击提交时,只提交了一个条目。第一个,我不确定我哪里出错了,任何帮助都会受到赞赏。

循环位于此代码块的底部,但我不确定问题是什么。

 <?php
session_start();

if (!isset($_SESSION["currentUserID"])) header("Location: login.php");

include('dbConnect.php');

$queryStr=("SELECT * FROM category");
    $dbParams=array();
  // now send the query
  $results  = $db->prepare($queryStr);
  $results->execute($dbParams);

  $dropDown = "";
  foreach($results as $category) {
        $dropdown .= '<option value="' . $category["category_id"] . '">' . $category["category_name"] . '</option>';
  }
?>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Welcome</title>

<TITLE>Category and Test</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
//Referenced for help --lines 81- 95
//https://www.codeproject.com/Questions/893365/Use-data-pulled-out-from-one-mysql-table-and-inser
//https://stackoverflow.com/questions/48270422/insert-values-into-database-from-form-with-drop-downs?noredirect=1#comment83524543_48270422

var numRows = 1;

function getTest(val,x) {
    $.ajax({
    type: "POST",
    url: "get_test.php",
    data:'category_id='+val,
    success: function(data){
        $("#test-list" + x).html(data);
    }
    });
}

function selectCategory(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}

// Referenced for help - https://www.youtube.com/watch?v=kBAPbCDGCuY

 var maxRows=5;
 var x = 1;

 // add rows
$(document).ready(function(e)
{    // add new row or fields
    $("#add").click(function(e)
    {   // if less than 5 then continue to add a new row
        if (x<=maxRows)
        { // add new row with all fields, update name with x to make unique and stop drop downs changing each others values
           var html = '<div class="row" id="container"><label>Category:</label><select name="category' + x + '" id="category-list" class="demoInputBox" onChange="getTest(this.value,' + x +');"><?php echo $dropdown; ?></select><label>Test:</label><select name="test' + x + '" id="test-list' + x + '" class="demoInputBox"><option value="">Select Test</option></select><label>Result:</label><input id="resultchild" class="input" name="result' + x + '" type="double" required><label>Date:</label><input id="datechild" class="input" name="date' + x + '" type="date" required ><label>Low Boundary:</label><input id="lowchild" class="input" name="low' + x + '" type="double" required><label>High Boundary:</label><input id="highchild" class="input" name="high' + x + '" type="double" required><a href ="#" id="remove"> X </a>';
           document.addTest1.count.value=x;
           // update x
           x++;
           // add html below as new row
           $("#container").append(html);
        }
    });
    // take away rows
    $("#container").on('click', '#remove', function(e)
    {
        $(this).parent('div').remove();
        x--;
        document.addTest1.count.value=x;
    });

    // populate values from first row

});

</script>
</head>
<body>
<!-- 
Reference for help -- lines 134 - 144
https://www.codeproject.com/Questions/893365/Use-data-pulled-out-from-one-mysql-table-and-inser
https://stackoverflow.com/questions/48270422/insert-values-into-database-from-form-with-drop-downs?noredirect=1#comment83524543_48270422
-->

<div class="row" id="container">
<label>Category:</label>
<select name="category0" id="category-list" class="demoInputBox" onChange="getTest(this.value,0);">
<option value="">Select Category</option>
<?php
 echo $dropdown;
?>
</select>
<form action="addTest.php" method="post" name="addTest1">
<input type="hidden" name ="count" value="0">
<label>Test:</label>
<select name="test0" id="test-list0" class="demoInputBox">
<option value="">Select Test</option>
</select>
<label>Result:</label><input id="result" class="input" name="result0" type="double" required>
<label>Date:</label><input id="date" class="input" id="date" name="date0" type="date" required>
<label>Low Boundary:</label><input id="low" class="input" name="low0" type="double" required>
<label>High Boundary:</label><input id="high" class="input" name="high0" type="double" required>

<a href ="#" id="add"> Add More</a>
<input class="submit" name="submit" type="submit" value="Submit">
</div>
</form>


<?php

if(isset($_POST['submit'])){

$count = $_POST['count'];
// for loop to iterate through each new row and insert into database
for ($x=0; $x<$count; $x++) {

    $currentUser      = $_SESSION["currentUserID"];
    $currentBloodTest = $_POST['test'.$x];
    $value            = $_POST['result'.$x];
    $date             = $_POST['date'.$x];
    $low            = $_POST['low'.$x];
    $high  = $_POST['high'.$x];

    $query = $db->prepare("INSERT INTO results (user_id, bloodtest_id, date, value, low_boundary, high_boundary)
                           VALUES (?, ?, ?, ?, ?, ?)");
    $query->execute( array($currentUser, $currentBloodTest, $date, $value, $low, $high) );
        echo "<br><br><span>Data Inserted successfully...!!</span>";
    } //end of for loop 
}

?>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

将您的html部分更改为此。

<form action="addTest.php" method="post" name="addTest1">
<input type="hidden" name ="count" value="0">
<label>Test:</label>
<select name="test0" id="test-list0" class="demoInputBox">
<option value="">Select Test</option>
</select>
<label>Result:</label><input id="result" class="input" name="result[]" type="double" required>
<label>Date:</label><input id="date" class="input" id="date" name="date[]" type="date" required>
<label>Low Boundary:</label><input id="low" class="input" name="low[]" type="double" required>
<label>High Boundary:</label><input id="high" class="input" name="high[]" type="double" required>

<a href ="#" id="add"> Add More</a>
<input class="submit" name="submit" type="submit" value="Submit">
</div>
</form>

在服务器端代码上,您应该使用foreach或使用表单输入控件名称中给出的数组。

看看这个 - &gt; Multiple Inputs with Same Control Name in PHP