【问题标题】:Insert into table using array method with parent ID使用带有父 ID 的数组方法插入表中
【发布时间】:2018-02-10 16:07:21
【问题描述】:

我正在尝试在插入之前检查数据库中的输入。但是,它在父表中插入了多个 id。它假设插入多个具有相同父 ID 的子父。我有 3 个子表,toto_number、damacai_number 和 magnum_number。你可以看看我提供的图片。我试图在插入之前检查数据库中的输入。这意味着它在插入数据库之前检查数字的可用性

界面视图

插入.php 文件

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

      foreach ($_POST['gamecenter'] as $key => $value) { // all game centers will be looped here
      $gamecenter = $_POST['gamecenter'][$key];
      $number     = $_POST['number'][$key];
      $price      = $_POST['price'][$key];
      $result     = mysqli_query($conn, "SELECT * FROM number_availability WHERE Number = '" . $number . "' AND GameCenter = '" . $gamecenter . "'");
      $row        = mysqli_fetch_assoc($result);

try {
    if ($row['Availability'] > 0) {
        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'][$key];
                    $price  = $_POST['price'][$key];

                    $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();
 ?>

//index.php
<?php
?>
<!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="test3.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" onclick="" 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="Check Number" />
     </div>
    </div>
   </form>
      </br>

  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="number[]" value="" 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><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></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){
        $(document.body).append(data);
    }

   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
    

    
</script>

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    这应该没问题。如果还有其他问题,请告诉我。

    <?php
    try {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "2d_system";
        $conn = new mysqli($servername, $username, $password, $dbname);
        if($stmt = $conn->prepare($conn, "SELECT `Availability` FROM `number_availability` WHERE `Number`=? AND `GameCenter`=?")){
            foreach($_POST['gamecenter'] as $key => $value){
                $gamecenter = $_POST['gamecenter'][$key];
                $number = $_POST['number'][$key];
                $stmt->bind_param('ii', $number, $gamecenter); // if any of these values is a String, use 's' for that value instead (ii means integer-integer)
                $stmt->execute();
                if($conn->errno){
                    throw new Exception("Error: could not check for availability: " . $conn->error);
                }
                $result = $stmt->get_result();
                $data = $result->fetch_array();
                if($data['Availability'] <= 0){
                    unset($_POST['gamecenter'][$key]);
                    unset($_POST['number'][$key]);
                    unset($_POST['price'][$key]);
                }
            }
        }
        if($conn->errno){
            throw new Exception("Error: could not check for availability: " . $conn->error);
        }
        if(count($_POST['gamecenter']) > 0){
            if($conn->query("INSERT INTO `lottery_ticket` (`CreatedDateTime`) VALUES (now())")){
                $lotteryTicketID = $conn->insert_id;
                foreach($_POST['gamecenter'] as $key => $value){
                    $gamecenter = $_POST['gamecenter'][$key];
                    $number = $_POST['number'][$key];
                    $price = $_POST['price'][$key];
                    if($stmt = $conn->prepare("INSERT INTO `" . strtolower($gamecenter) . "_draw` (`LotteryId`, `" . $gamecenter . "_Number`, `Price`) VALUES (?, ?, ?)")){
                        $stmt->bind_param('idd', $lotteryTicketID, $number, $price);
                        $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.";
        } else {
            throw new Exception("Error: no available numbers.");
        }
    } catch(Exception $e){
        echo $e->getMessage();
    }
    $conn->close();
    ?>
    

    顺便说一句,在继续开发之前,请阅读有关参数化语句的更多信息。另外,试着理解我给你的代码并阅读 cmets。上次我几乎改变了一切,我可以在这个问题中看到你忽略了所有这些。此外,您似乎不了解代码的逻辑,因此请考虑一下。尝试在纸上写下每个算法,然后测试该算法,然后基于该算法构建您的应用程序。

    【讨论】:

    • 嘿@zeke 再次感谢您的回复。我测试了上面给出的代码,并且存在一些问题。即使列 'Availability' = 0,记录仍会插入到 'lottery_ticket' 中。如果数字不可用,则不应在父表 (lottery_ticket) 上创建条目,因为这只会创建一个“空”条目。我将研究参数化语句并尝试将其应用于我的代码。是的,我确实在编写代码之前写下了算法。然而,由于我缺乏知识,我走到了死胡同。
    • 让我明白这一点,当您为每个游戏中心插入一个条目时,您要创建多少张彩票?
    • 一次提交一张彩票,但如果所有号码都不可用,则不会创建任何彩票条目
    • 如果它适用于一个游戏中心而不适用于其他游戏中心怎么办?
    • 在这种情况下,它将创建一张彩票,
    猜你喜欢
    • 2022-11-25
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多