[英]Inserting array of data in database
我有兩個值數組:
第一個數組包含用戶 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 在不同的行中插入這些值?
只需你可以這樣做
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");
}
}
對於您的預期目的,一旦您在數組中擁有 $uid 和 $stat 的值,您就可以執行以下操作:
<?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]
));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.