使用数组方法插入表中

时间:2018-01-28 15:40:17

标签: php mysql sql

1如何根据下拉列表插入查询?我的数据库由4个表,一个父表和3个子表组成。我的下拉列表包含Table1Table2Table3。如果选择Table3,则会将数据插入Table3

当我尝试插入单个输入字段时它工作正常,但是当我尝试插入多个输入时,它只会存储最后选择的表。

查看我存储的表单here

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "2d_system";
    $conn = new mysqli($servername, $username, $password, $dbname);



  $sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
   mysqli_query($conn, $sql);

  foreach($_POST['gamecenter'] as $i => $gamecenter){
  $gamecenter = $_POST['gamecenter'][$i];
  $number = $_POST['number'][$i];
  $price = $_POST['price'][$i];

//checks type of gamecenter if true, insert
  if ($gamecenter == 'Damacai'){ 
try {
  //to insert into parent table
  //$sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
 // mysqli_query($conn, $sql);
  $queryDamacai = "INSERT INTO damacai_draw (LotteryId, Damacai_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

  if(!mysqli_query($conn, $queryDamacai)){  
   throw new Exception("error: could not able to execute $queryDamacai. " . mysqli_error($conn));
 }

 echo "Records added successfully.";
  }
      catch(Exception $e)
   {
      echo $e->getMessage();
   }
  }

      //checks type of gamecenter if true, insert
       if ($gamecenter == 'Magnum'){ 
          try {
         //to insert into parent table
           //$sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES 
      (now())";
     //mysqli_query($conn, $sql);

$queryMagnum = "INSERT INTO magnum_draw (LotteryId, Magnum_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

if(!mysqli_query($conn, $queryMagnum)){  
  throw new Exception("error: could not able to execute $queryMagnum. " . mysqli_error($conn));
}

     echo "Records added successfully.";
   }
   catch(Exception $e)
 {
   echo $e->getMessage();
 }
}

//checks type of gamecenter if true, insert
 if ($gamecenter == 'Toto'){ 
   try{

<?php
//index.php

$connect = new PDO("mysql:host=localhost;dbname=2d_system", "root", "");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>2D</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <br />
   <h4 align="center">Enter Number Details</h4>
   <br />
   <form method="post" id="insert_form" action="insert.php">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>2D Number</th>
       <th>Price (RM)</th>
       <th>Game Center</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Print" />
     </div>
    </div>
   </form>
   <form method="post" action="collect_vals.php">
   
   
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="number[]" class="form-control item_name" /></td>';
  html += '<td><input type="text" name="price[]" class="form-control item_quantity" /></td>';
  html += '<td><select name="gamecenter[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.number').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.price').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.gamecenter').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>

//插入父表

$queryToto = "INSERT INTO toto_draw (LotteryId, Toto_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

if(!mysqli_query($conn, $queryToto)){  
  throw new Exception("error: could not able to execute $queryToto. " . mysqli_error($conn));
}

    echo "Records added successfully.";
 }
 catch(Exception $e)
 {
     echo $e->getMessage();
  }
  }



   } 

    $conn->close();
     ?>

2 个答案:

答案 0 :(得分:0)

跳转到#34; EDIT&#34;实际答案

你的foreach循环只更新查询字符串...但是从不执行它,所以你一直这样做直到最后一条记录,然后你运行查询...这就是为什么它只存储最后一个输入。

对于我的例子,我只会使用Damacai游戏中心,但它适用于所有游戏中心。尝试运行代码并在无法执行查询时抛出异常。如果所有查询都正确运行,则会显示成功消息:

<?php
if($gamecenter == 'Damacai'){
    try {
        $sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
        mysqli_query($conn, $sql);

        foreach($_POST['number'] as $i => $number){
            // Get values from post.
            $number = mysqli_real_escape_string($conn, $number);
            $price = mysqli_real_escape_string($conn, $_POST['price'][$i]);

            // Add to database
            $queryDamacai = "INSERT INTO damacai_draw (LotteryId, Damacai_Number, Price) VALUES (last_insert_id(), '$number', '$price')";
            //$queryDamacai = substr($queryDamacai, 0, -1); //remove last char
            //$result = mysqli_query($conn, $query);

            if(!mysqli_query($conn, $queryDamacai)){
                throw new Exception("error: could not able to execute $queryDamacai. " . mysqli_error($conn));
            }
        }
        echo "records added successfully.";
    } catch(Exception $e){
        echo $e->getMessage();
    }
}
?>

请务必注意,如果您想同时存储多个游戏中心的数据,则不应使用if () {} else if () {},而应为每个游戏中心创建单独的if语句。否则,只会修改一个游戏中心。另外,再看一下你如何使用$gamecenter,因为你觉得它听起来像是一个数组。

修改

所以信息没有像我想象的那样被发送......我相信我得到了这个想法,尽管事实上我不知道为什么用这么多jQuery来创建表单。无论如何,这是我认为应该工作的整个(是的,对于所有游戏中心)代码。您仍然需要确保[$k] $_POST['gamecenter']确实需要foreach,因为我相信,如果<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "2d_system"; $conn = new mysqli($servername, $username, $password, $dbname); try { if($conn->query("INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())")){ // consider adding a default value of CURRENT_TIMESTAMP for CreatedDateTime $lotteryTicketID = $conn->insert_id; foreach($_POST['gamecenter'] as $k => $v){ // all game centers will be looped here $gamecenter = $_POST['gamecenter'][$k]; // make sure you need this, if the values are incorrect, then consider using $gamecenter = $v; if($stmt = $conn->prepare("INSERT INTO ".strtolower($gamecenter)."_draw (LotteryId, ".$gamecenter."_Number, Price) VALUES (?, ?, ?)")){ // This part is done to avoid creating so many duplicated queries and and shorten the code. $number = $_POST['number'][$k]; $price = $_POST['price'][$k]; $stmt->bind_param('idd', $lotteryTicketID, $number, $price); // be careful with these values. If you change the name of your tables or columns, these might be affected. $stmt->execute(); } if($conn->errno){ throw new Exception("Error: could not execute query/queries: ".$conn->error); } } } if($conn->errno){ throw new Exception("Error: could not execute query/queries: ".$conn->error); } echo "Records added successfully."; } catch(Exception $e){ echo $e->getMessage(); } $conn->close(); ?> 设置为同时提供密钥和值,则我不相信,需要使用循环元素的键。但是对于你的具体案例我可能是错的。

没有进一步的到期,代码:

<?php
    if(isset($_POST["btn1"])){  
        echo "btn1";
        die();
    }   
?>
<html>
    <body>
        <button id="btn1" name="btn1">btn1</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("#btn1").click(function(){
                    $.ajax({
                        type:'post',
                        url:'',
                        data:{'btn1':true},
                        datatype:'text',
                        success:function(val){
                            alert(val);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

答案 1 :(得分:0)

首先检查您如何获取gamecenter字段的后期值。您在此处将其用作多个动态字段,因此您需要以动态方式命名您的字段,例如gamecenter[]而不是静态名称.if如果它是静态的,那么它的值将是静态的并被覆盖。您需要重命名该字段,以便它可以表示动态名称。您可以通过按行号访问索引来获取值。 所以你需要做一个foreach来抓住正确的$_POST['gamecenter'][i]然后应用你的条件。我认为它会正常工作。

谢谢你。如果下次发生任何问题,请告诉我。