如何使用PHP将多个数据插入数据库?

时间:2017-11-20 13:42:35

标签: javascript php mysql

$(document).ready(function() {
  $(document).on('keyup', '.nsp, .curr_sales', recalculate);

  function findParseInput(el, selector) {
    return parseFloat($(el).find(selector).val());
  }

  function calculateRow(row) {
    var nsp = findParseInput(row, '.nsp');
    var curr_sales = findParseInput(row, '.curr_sales');
    return Number.isNaN(nsp) || Number.isNaN(curr_sales) ? 0 : nsp * curr_sales;
  }

  function getTotal() {
    return $('#example tr')
      .toArray()
      .map(calculateRow)
      .reduce(function(a, b) {
        return a + b;
      }, 0);
  }

  function recalculate() {
    $("#totalCS").val(getTotal());
  };

  $(document).on('keyup', '.nsp, .close_bal', recalculatee);

  function findParseInput(el, selector) {
    return parseFloat($(el).find(selector).val());
  }

  function calculateRoww(row) {
    var nsp2 = findParseInput(row, '.nsp');
    var close_bal = findParseInput(row, '.close_bal');
    return Number.isNaN(nsp2) || Number.isNaN(close_bal) ? 0 : nsp2 * close_bal;
  }

  function getTotall() {
    return $('#example tr')
      .toArray()
      .map(calculateRoww)
      .reduce(function(a, b) {
        return a + b;
      }, 0);
  }

  function recalculatee() {
    $("#totalCB").val(getTotall());
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
<form name="registration" id="myForm" action="" method="post" class="form-inline">
  <div class="form-row">
    <div class="form-group col-md-4">
      <label class="sr-only" for="inlineFormInput">Distributor Name</label>

      <select id="distributor_name" class="form-control" required>
                                <option value="">Select a Distributor:</option>
                                <option value="1 ">NATIONAL</option><option value="2 ">Sunny Enterprises</option><option value="3 ">Sajjad Enterprises</option><option value="4 ">Hassan Traders</option></select></div>
    <div class="form-group col-md-4">
      <input class="date-own form-control" style="width: 300px;" type="text" placeholder="Select Month" id="date" required>
    </div>
    <table id="example">
      <thead class="thead-inverse">
        <tr>
          <th>#</th>
          <th>Product Name</th>
          <th>NSP</th>
          <th>Current Sales</th>
          <th>Closing Balance</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope='row'><input type='text' id='pro_id' size=4 value=175 disabled></th>
          <td><input type='text' name='pro_name' value=AMBIEN 10 MG disabled></td>
          <td><input type='text' class=nsp name='nsp' size=4 value=230 disabled></td>
          <td><input type="number" class="curr_sales" size="5" name="curr_sales" value="0" required></td>
          <td><input type="number" class="close_bal" size="5" name="close_bal" value="0" required></td>
        </tr>
        <th scope='row'><input type='text' id='pro_id' size=4 value=176 disabled></th>
        <td><input type='text' name='pro_name' value=AZISOFT 250MG disabled></td>
        <td><input type='text' class=nsp name='nsp' size=4 value=191 disabled></td>
        <td><input type="number" class="curr_sales" size="5" name="curr_sales" value="0" required></td>
        <td><input type="number" class="close_bal" size="5" name="close_bal" value="0" required></td>
        </tr>
        <th scope='row'><input type='text' id='pro_id' size=4 value=177 disabled></th>
        <td><input type='text' name='pro_name' value=AZISOFT 500MG disabled></td>
        <td><input type='text' class=nsp name='nsp' size=4 value=191 disabled></td>
        <td><input type="number" class="curr_sales" size="5" name="curr_sales" value="0" required></td>
        <td><input type="number" class="close_bal" size="5" name="close_bal" value="0" required></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th></th>
          <th></th>
          <th></th>
          <th>
            <div class="input-group">
              <span class="input-group-addon">Total Current Sales</span>
              <input type="number" name="amount" size="5" id='totalCS' readonly class="form-control">
            </div>
          </th>
          <th>
            <div class="input-group">
              <span class="input-group-addon">Total Closing Balance</span>
              <input type="number" name="amount" size="5" id='totalCB' readonly class="form-control">
            </div>
          </th>
        </tr>
      </tfoot>
    </table>
    <button type="submit" id="save" name="save" class="btn btn-primary">Save</button>
  </div>
</form>

<script type="text/javascript">
  $('.date-own').datepicker({
    // minViewMode: 1,
    format: 'yyyy-mm-dd',
    autoclose: true
  });
</script>
<div id="congrats"></div>

这是我的表格和表单数据,我希望使用PHP将此数据发送到数据库,这是使用此查询,但它只插入第1列而不是所有列数据。

<?php
$con = mysqli_connect("localhost", "root", "", "del");
//Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$distributor_name = $_POST["distributor_name"];
$date = $_POST["date"];
$totalCS = $_POST["totalCS"];
$totalCB = $_POST["totalCB"];
if (isset($_POST["curr_sales"]) && is_array($_POST["curr_sales"])) {
    $curr_sales = implode(",", $_POST["curr_sales"]);
}
foreach($_POST["curr_sales"] as $key => $text_field){
        $curr_sales .= $text_field .", ";
}

if (isset($_POST["close_bal"]) && is_array($_POST["close_bal"])) {
    $close_bal = implode(",", $_POST["close_bal"]);
}
foreach($_POST["close_bal"] as $key => $text_field){
        $close_bal .= $text_field .", ";
 }

if (isset($_POST["nsp"]) && is_array($_POST["nsp"])) {
    $nsp = implode(",", $_POST["nsp"]);
}
foreach($_POST["nsp"] as $key => $text_field){
        $nsp .= $text_field .", ";
 }


if (isset($_POST["pro_id"]) && is_array($_POST["pro_id"])) {
    $pro_id = implode(",", $_POST["pro_id"]);
}
foreach($_POST["pro_id"] as $key => $text_field){
        $pro_id .= $text_field .", ";
 }


$stmt = $con->prepare("INSERT INTO `orders`(`d_id`, `order_date`, `current-sales`, `closing-balance`, `total_cs`, `total_cb`, `nsp`, `pro_id`) VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("isiiiiii", $distributor_name, $date, $curr_sales, $close_bal, $totalCS, $totalCB, $nsp, $pro_id);
if ($stmt->execute()) {
    echo 'Succefully Submitted';
};
$stmt->close();
  

当我使用此代码时,它可以工作,但只插入表的第一行数据。我想用选定的分配器,日期,totalCS和totalCB插入所有行的数据。请帮忙。

2 个答案:

答案 0 :(得分:0)

  • <th>不允许在该位置(<tbody>内)
  • 请勿正确使用</tr>标记关闭行
  • 您从$ _POST获取的某些输入标记为disabled,因此它们不会出现在$ _POST
  • 在html属性中使用""代替''并始终使用
  • input名称都是相同的,所以在提交过程中它们是 用提交的最后一个值(最后一行)覆盖
  • 你需要$ _POST中包含所有行的param数组并循环它 用于在DB中插入的参数
  • 你在文档中声明了JS函数,我建议在外面声明。

看看这个:

function findParseInput(el, selector) {
    return parseFloat($(el).find(selector).val());
}

function calculateRow(row) {
  var nsp = findParseInput(row, '.nsp');
  var curr_sales = findParseInput(row, '.curr_sales');
  return Number.isNaN(nsp) || Number.isNaN(curr_sales) ? 0 : nsp * curr_sales;
}

function getTotal() {
  return $('#example tr')
    .toArray()
    .map(calculateRow)
    .reduce(function(a, b) {
      return a + b;
    }, 0);
}

function findParseInput(el, selector) {
  return parseFloat($(el).find(selector).val());
}

function calculateRoww(row) {
  var nsp2 = findParseInput(row, '.nsp');
  var close_bal = findParseInput(row, '.close_bal');
  return Number.isNaN(nsp2) || Number.isNaN(close_bal) ? 0 : nsp2 * close_bal;
}

function getTotall() {
  return $('#example tr')
    .toArray()
    .map(calculateRoww)
    .reduce(function(a, b) {
      return a + b;
    }, 0);
}

function recalculate() {
  $("#totalCS").val(getTotal());
};

function recalculatee() {
  $("#totalCB").val(getTotall());
}
  
$(document).ready(function() {
  $(document).on('keyup', '.nsp, .curr_sales', recalculate);

  $(document).on('keyup', '.nsp, .close_bal', recalculatee);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
<form name="registration" id="myForm" action="" method="post" class="form-inline">
    <div class="form-row">
        <div class="form-group col-md-4">
            <label class="sr-only" for="distributor_name">Distributor Name</label>
            <select id="distributor_name" name="distributor_name" class="form-control" required>
                <option value="">Select a Distributor:</option>
                <option value="1 ">NATIONAL</option>
                <option value="2 ">Sunny Enterprises</option>
                <option value="3 ">Sajjad Enterprises</option>
                <option value="4 ">Hassan Traders</option>
            </select>
        </div>
        <div class="form-group col-md-4">
            <input class="date-own form-control" name="date" style="width: 300px;" type="text" placeholder="Select Month" id="date" required>
        </div>
        <table id="example">
            <thead class="thead-inverse">
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>NSP</th>
                <th>Current Sales</th>
                <th>Closing Balance</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td><input type="text" id="pro_id" name="rows[175][pro_id]" size="4" value="175"></td>
                <td><input type="text" name="rows[175][pro_name]" value="AMBIEN 10 MG"></td>
                <td><input type="text" class=nsp name="rows[175][nsp]" size="4" value="230"></td>
                <td><input type="number" class="curr_sales" size="5" name="rows[175][curr_sales]" value="0" required></td>
                <td><input type="number" class="close_bal" size="5" name="rows[175][close_bal]" value="0" required></td>
            </tr>
            <tr>
                <td><input type="text" id="pro_id" name="rows[176][pro_id]" size="4" value="176"></td>
                <td><input type="text" name="rows[176][pro_name]" value="AZISOFT 250MG"></td>
                <td><input type="text" class=nsp name="rows[176][nsp]" size="4" value="191"></td>
                <td><input type="number" class="curr_sales" size="5" name="rows[176][curr_sales]" value="0" required></td>
                <td><input type="number" class="close_bal" size="5" name="rows[176][close_bal]" value="0" required></td>
            </tr>
            <tr>
                <td><input type="text" id="pro_id" name="rows[177][pro_id]" size="4" value="177"></td>
                <td><input type="text" name="rows[177][pro_name]" value="AZISOFT 500MG"></td>
                <td><input type="text" class=nsp name="rows[177][nsp]" size="4" value="191"></td>
                <td><input type="number" class="curr_sales" size="5" name="rows[177][curr_sales]" value="0"></td>
                <td><input type="number" class="close_bal" size="5" name="rows[177][close_bal]" value="0"></td>
            </tr>
            </tbody>
            <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th>
                    <div class="input-group">
                        <span class="input-group-addon">Total Current Sales</span>
                        <input type="number" name="amount" size="5" id="totalCS" readonly class="form-control">
                    </div>
                </th>
                <th>
                    <div class="input-group">
                        <span class="input-group-addon">Total Closing Balance</span>
                        <input type="number" name="amount" size="5" id="totalCB" readonly class="form-control">
                    </div>
                </th>
            </tr>
            </tfoot>
        </table>
        <button type="submit" id="save" name="save" class="btn btn-primary">Save</button>
    </div>
</form>
<script type="text/javascript">
	$('.date-own').datepicker({
		// minViewMode: 1,
		format: 'yyyy-mm-dd', autoclose: true
	});
</script>
<div id="congrats"></div>

PHP(我建议使用一个事务来插入多行,但我制作一个没有事务的简单代码)

<?php
$con = mysqli_connect("localhost", "root", "", "del");

//Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

foreach ($_POST['rows'] as $rowId => $columns) {
    $stmt = $con->prepare("INSERT INTO `orders`(`d_id`, `order_date`, `current-sales`, `closing-balance`, `total_cs`, `total_cb`, `nsp`, `pro_id`) VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isiiiiii", $_POST['distributor_name'], $_POST['date'], $columns['curr_sales'],
        $columns['close_bal'], $_POST['totalCS'], $_POST['totalCB'], $columns['nsp'], $columns['pro_id']);
    $stmt->execute();
}
?>

答案 1 :(得分:-1)

您可以使用以下解决方案获得一个想法,这可以进一步增强。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css"
      rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
<form name="registration" id="myForm" action="" method="post" class="form-inline">
    <div class="form-row">
        <div class="form-group col-md-4">
            <label class="sr-only" for="inlineFormInput">Distributor Name</label>

            <select id="distributor_name" class="form-control" required>
                <option value="">Select a Distributor:</option>
                <option value="1 ">NATIONAL</option>
                <option value="2 ">Sunny Enterprises</option>
                <option value="3 ">Sajjad Enterprises</option>
                <option value="4 ">Hassan Traders</option>
            </select></div>
        <div class="form-group col-md-4">
            <input class="date-own form-control" style="width: 300px;" type="text" placeholder="Select Month" id="date"
                   required>
        </div>
        <table id="example">
            <thead class="thead-inverse">
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>NSP</th>
                <th>Current Sales</th>
                <th>Closing Balance</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <th scope='row'><input type='text' id='pro_id' name='pro_name[]' size=4 value=175 disabled></th>
                <td><input type='text' name='pro_name[]' value=AMBIEN 10 MG disabled></td>
                <td><input type='text' class=nsp name='nsp[]' size=4 value=230 disabled></td>
                <td><input type="number" class="curr_sales" size="5" name="curr_sales[]" value="0" required></td>
                <td><input type="number" class="close_bal" size="5" name="close_bal[]" value="0" required></td>
            </tr>
            <th scope='row'><input type='text' id='pro_id' name='pro_name[]' size=4 value=176 disabled></th>
            <td><input type='text' name='pro_name[]' value=AZISOFT 250MG disabled></td>
            <td><input type='text' class=nsp name='nsp[]' size=4 value=191 disabled></td>
            <td><input type="number" class="curr_sales" size="5" name="curr_sales[]" value="0" required></td>
            <td><input type="number" class="close_bal" size="5" name="close_bal[]" value="0" required></td>
            </tr>
            <th scope='row'><input type='text' id='pro_id' name='pro_name[]' size=4 value=177 disabled></th>
            <td><input type='text' name='pro_name[]' value=AZISOFT 500MG disabled></td>
            <td><input type='text' class=nsp name='nsp[]' size=4 value=191 disabled></td>
            <td><input type="number" class="curr_sales" size="5" name="curr_sales[]" value="0" required></td>
            <td><input type="number" class="close_bal" size="5" name="close_bal[]" value="0" required></td>
            </tr>
            </tbody>
            <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th>
                    <div class="input-group">
                        <span class="input-group-addon">Total Current Sales</span>
                        <input type="number" name="amount" size="5" id='totalCS' readonly class="form-control">
                    </div>
                </th>
                <th>
                    <div class="input-group">
                        <span class="input-group-addon">Total Closing Balance</span>
                        <input type="number" name="amount" size="5" id='totalCB' readonly class="form-control">
                    </div>
                </th>
            </tr>
            </tfoot>
        </table>
        <button type="submit" id="save" name="save" class="btn btn-primary">Save</button>
    </div>
</form>

<script type="text/javascript">
    $('.date-own').datepicker({
        // minViewMode: 1,
        format: 'yyyy-mm-dd',
        autoclose: true
    });
</script>
<div id="congrats"></div>

请注意,在所有输入文本名称中都为[]来保存字段的多个值。

<?php
$con = mysqli_connect("localhost", "root", "", "del");
//Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$dbValues         = [];
$distributor_name = $_POST["distributor_name"];
$date             = $_POST["date"];
$totalCS          = $_POST["totalCS"];
$totalCB          = $_POST["totalCB"];

$currSales = $_POST["curr_sales"] ?? [];
$closeBal  = $_POST["close_bal"] ?? [];
$nsp       = $_POST["nsp"] ?? [];
$proIds    = $_POST["pro_id"] ?? [];

$currSalesCount = count($currSales);//Assumed the current sales count is equal to other variables
//validate the count of all above array is same
for ($i = 0; $i < $currSalesCount; $i++) {
    //If you want to add some sql injection you can do it here
    $dbValues[] = "('{$distributor_name}','{$date}','{$currSales[$i]}','{$closeBal[$i]}','{$totalCS}','{$totalCB}','{$nsp[$i]}','$proIds[$i]')";
}

$strDbValues    = implode(',',$dbValues);

//No need to bind params directory execute this bulk query
$stmt = $con->prepare("INSERT INTO `orders`(`d_id`, `order_date`, `current-sales`, `closing-balance`, `total_cs`, `total_cb`, `nsp`, `pro_id`) VALUES $strDbValues");
if ($stmt->execute()) {
    echo 'Succefully Submitted';
};
$stmt->close();