来自爆炸的Codeigniter和insert_batch

I have this code:

    function insertGenre() {
    $genres = explode(',',$this->input->post('genreName'));

    foreach($genres as $genre) {
        $temp = array(
            'id' => null,
            'name' => $genre,
            'popular' => '0'
        );

        $data2[] =  $temp;
    }

    return $data2;

    $data = array(
        'id' => null,
        'name' => $this->input->post('genreName'),
        'popular' => '0'
    );

    //$this->db->insert('genres',$data);
    $this->db->insert_batch('genres',$data2);
}

It should run just fine (I ran through a couple of questions in here), but it doesn't. What am I doing wrong?

Shouldn't it be something like this:

function insertGenre() {
    $genres = explode(',',$this->input->post('genreName'));

    foreach($genres as $genre) {
        $temp = array(
            'id' => null,
            'name' => $genre,
            'popular' => '0'
        );
        $data2[] =  $temp;
    }

    if( $this->db->insert_batch('genres',$data2) ) {
        return $data2;
    } else {
        return false;
    }
}

You were returning before you ran the insert query. The second $data variable also seems to be redundant.

I also added the if statement at the end which will return false if the insert fails.

You need to move your return to the end of the function, otherwise it will never execute the lines below it:

function insertGenre() {
    $genres = explode(',',$this->input->post('genreName'));

    foreach($genres as $genre) {
        $temp = array(
            'id' => null,
            'name' => $genre,
            'popular' => '0'
        );

        $data2[] =  $temp;
    }

    $data = array(
        'id' => null,
        'name' => $this->input->post('genreName'),
        'popular' => '0'
    );

    //$this->db->insert('genres',$data);
    $this->db->insert_batch('genres',$data2);

    return $data2;
}