2017-10-15 59 views
1

我有值的兩個數組:插入數據的陣列中的數據庫

第一個數組包含用戶ID:

Array ([0]=>1 [1]=>2 [2]=>3 [3]=>4 [4]=>5 [5]=>6) 

第二個數組包含考勤狀態:

Array([0]=>Present [1]=>Absent [2]=>Absent [3]=>Present [4]=>Absent [5]=>Present) 

我想插入這些值在數據庫中分開,如下所示:

U_id      Status 

1       Present 
2       Absent 
3       Absent 
4       Present 
5       Absent 
6       Present  

目前,我正在使用此代碼在數據庫中插入值。

我的控制器代碼:

public function usr_att(){ 
    if(isset($_POST['submit'])){ 

     $uid = $_POST['uid']; 
     $status= $_POST['stat']; 
     $id = implode("," , $uid); 
     $status = implode("," , $status); 
     $data = array (
      'u_id' => $id, 
      'status' => $status 
     ); 
     $this->db->insert('attendence' , $data); 
     redirect("usr/usr_list", "refresh"); 
    } 
} 

但此代碼插入數據是這樣的:

U_id    Status 

1     Present,Absent,Absent,Present,Absent,Present 

我如何可以插入使用CodeIgniter的不同行這些價值觀?

+0

什麼您使用的是PHP版本嗎? –

回答

1

只要你能做到這樣

public function usr_att() 
{ 
    if(isset($_POST['submit'])) 
    { 
     $uid = $_POST['uid']; 
     $status = $_POST['stat']; 

     foreach ($uid as $key => $item) 
     { 
      $data = array (
       'u_id' => $item, 
       'status' => $status[$key] 
      ); 
      $this->db->insert('attendence' , $data); 
     } 
     redirect("usr/usr_list", "refresh"); 
    } 
} 
+0

謝謝先生您的幫助,根據我的要求工作。 –

+0

@sameedulhassan謝謝。樂於幫助 –

0

爲了您的預期目的,一旦你有一個數組$ uid和$統計值,那麼你可以這樣做:

<?php 

// You have your u_id values in an array 
$uid = array('1','2','3','4','5','6'); 

// You have your status values in an array 
$stat = array('Present', 'Absent', 'Absent', 'Present', 'Absent', 'Present'); 

// As long as the number of u_id values and status values are the same 
if(count($uid) == count($stat)) 
{ 
    // Use the count of uid values and loop through 
    for($x = 0; $x <= count($uid) -1; $x++) 
    { 
     // Entering each on in the database 
     $this->db->insert('attendence', array(
      'u_id' => $uid[$x], 
      'status' => $stat[$x] 
     )); 
    } 
}