【问题标题】:Inserting array of data in database在数据库中插入数据数组
【发布时间】:2026-01-13 02:50:01
【问题描述】:

我有两个值数组:

第一个数组包含用户 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 将这些值插入到单独的行中?

【问题讨论】:

  • 你使用的是什么版本的 PHP?

标签: php database codeigniter insert


【解决方案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");
    }
}

【讨论】:

  • 谢谢先生您的帮助,它按照我的要求工作。
【解决方案2】:

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

【讨论】: