在数据库中插入数据数组

时间:2017-10-15 15:16:24

标签: php database codeigniter insert

我有两个值数组:

第一个数组包含用户ID&#; s:

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在单独的行中插入这些值?

2 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分:0)

出于预期目的,一旦你在数组中得到$ 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]
        ));
    }
}