codeigniter 如何在php中插入数据库后获取最后一个id

brtdzjyr  于 2022-12-07  发布在  PHP
关注(0)|答案(2)|浏览(156)

这里我将数据保存到数据库的多行中,我想检索每行的最后一个id,我该怎么做呢?
例如:print_r输入数据时结果。

Array
(
    [0] => Array
        (
            [name] => metode 11
            [description] => DESC 1
        )

    [1] => Array
        (
            [name] => metode 22
            [description] => DESC 2
        )

    [2] => Array
        (
            [name] => metode 33
            [description] => DESC 1
        )
)

在数据库中

id | name      | description
1    metode 11   desc 1
2    metode 22   desc 2
3    metode 33   desc 3

完成输入后,我想把每个id和这个我的代码

$data = array(); 
$numrow = 1;
foreach ($sheet as $row) {
    if ($numrow > 1) {
        array_push($data, array(
                'name'              => $row['A'],
                'description'       => $row['B'],
        ));
    }
    $numrow++;
}

$this->db->insert_batch('my_tabel', $data);
$myid =$this->db->insert_id();
//after insert i retrieve id using last_id() function, however, only last id is fetched, i want to fetch each id

$data_1 = array();
$numrow2 = 1;

foreach ($sheet as $row) {
    if ($numrow2 > 1) {
        array_push($data_1, array(
            'id_last'  => $myid,
            'id'     => $row['E'],
            'barang' => $row['F'],
        ));
    }
    $numrow2++;
}

我想这样:

Array
        (
            [0] => Array
                (
                    [last_id] => 1
                    [id] => 33
                    [barang] => ccc
                )
        
            [1] => Array
                (
                    [last_id] => 2
                    [id] => 44
                    [barang] => dd
                )
        
            [2] => Array
                (
                    [last_id] => 3
                    [id] => 55
                    [barang] => eee
                )
        )

提前感谢那些已经回答的人我希望我说的足够清楚

bogh5gae

bogh5gae1#

为什么不逐行插入而不是成批插入呢?从每次插入构建一个字典,以便稍后将其配对回来。

$data = array(); 
$numrow = 1;
foreach ($sheet as $row) {
    if ($numrow > 1) {
        array_push($data, array(
                'name'              => $row['A'],
                'description'       => $row['B'],
        ));
    }
    $numrow++;
}
$array_of_insert_id = array();

foreach ($data as $index => $data_to_insert) {
    $this->db->insert('my_tabel', $data_to_insert);
    $array_of_insert_id[$index] = $this->db->insert_id();
}

$data_1 = array();
$numrow2 = 1;
$counter = 0;

foreach ($sheet as $row) {
    if ($numrow2 > 1) {
        array_push($data_1, array(
            'id_last'  => $array_of_insert_id[$counter],
            'id'     => $row['E'],
            'barang' => $row['F'],
        ));
    }
    $numrow2++;
    $counter++;
}
bihw5rsg

bihw5rsg2#

//table field with input field data array
$table_data = [
   'table_field1' => $input_data1,
   'table_field2' => $input_data2,
];

//insert data in database 
$this->db->insert('table_name',$table_data);

//after insert return id
return $inserted_id = $this->db->insert_id();

相关问题