2017-05-10 142 views
0

我有這些表中的數據庫:插入到連接表的mysqli接力

country: id country 

和我有段表:

segments: id segment 

和第三臺名爲countrysegments有外鍵:國家ID相關與country.id相關的country.id和segment_id

countrysegments:  id country_id segment_id 

in index.php我有這個:

<div class="col-md-12"> 
      <table id="tbl" class = "table table-bordered table-responsive "> 
      <thead> 

          <th class="text-center">country</th> 

          <th class="text-center">segments</th> 
      </thead> 
      <tbody> 
      <?php 

       require 'class.php'; 

       $conn = new db_class(); 
       $read = $conn->select(); 
            $test = $conn->read(); 

       while($fetch = $read->fetch_array()){      
            ?> 

</td><td><select name="" id=""> 
      <?php 
      $reads = $conn->read(); 

      while($fetch = $reads->fetch_array()){ 
       ?> 

      <option><?php echo $fetch['segment']?></option> 

      <?php }?> 

    </select> 
    </td> </tr> 

          <?php  } 



     ?> 




     </tbody> 
    </table> 
      <form action="activate.php" method="post"> 
      <button class="btn btn-danger" name="save">Save</button> 

我有內部聯接三個表像這樣class.php:

  public function selectFrom(){ 
     $stmt = $this->conn->prepare("select * from countrysegments 
    inner join country on countrysegments.country_id = country.id 
    inner join segments on countrysegments.segment_id = segments.id") or die($this->conn->error); 
     if($stmt->execute()){ 
      $result = $stmt->get_result(); 
      return $result; 
     } 
    } 

的問題是,我必須插入countrysegment表什麼everycountry有選擇的段

只是我需要查詢的幫助和如何才能完成它感謝ü

+0

ü可以格式化代碼 –

+0

你能告訴什麼需要插入countrysegments表中。 或顯示錶的所期望的結果。 – Mack4Hack

+0

每個國家都必須有一個片段,所以我必須插入該國的ID和表countrysegments @ Mack4Hack – eddy

回答

0

假設你已經張貼值正常,試試這個下面的代碼

$country_id = $_REQUEST['country_id']; 
$segment_id = $_REQUEST['segment_id']; 

$stmt = $conn->prepare("INSERT INTO countrysegments (country_id, segment_id) VALUES (?, ?)"); 
$stmt->bind_param("ii", $country_id, $segment_id); 

$stmt->execute(); 
$stmt->close(); 
+0

我需要對每一個國家內部的段的ID選擇一個段,所以我有myltiple國家和多個片段,所以我需要做一個for循環,但我不知道該怎麼做,使用 – eddy

+0

你指的是貼陣列會是這樣 陣列(「國家1」 =>陣列(「segemtn1」,「分段2」),「COUNTRY2」陣列=>陣列( 'segement1', '分段2', '段3')) – Mack4Hack