2012-08-03 115 views
-2

我有這樣的代碼:笨和insert_batch從爆炸

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); 
} 

它應該運行得很好(我通過一對夫婦的問題在這裏跑),但事實並非如此。我究竟做錯了什麼?

+0

它應該做什麼?作爲輸出你期望什麼?它實際上做了什麼? [你有什麼嘗試](http://www.whathaveyoutried.com/)? – Matt 2012-08-03 12:57:32

+2

此外,你**做**認識到你的函數'返回''$ data2'並且永遠不會執行它下面的行,不是嗎? – Matt 2012-08-03 12:58:21

+0

刷新自己['return'](http://php.net/manual/en/function.return.php)的功能。 (這是一個鏈接,BTW)。 – Matt 2012-08-03 13:00:27

回答

1

它不應該是這樣的:

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; 
    } 
} 

在運行插入查詢之前,您正在返回。變量的第二個$data也似乎是多餘的。

我還在末尾添加了if語句,如果插入失敗,將返回false。

0

您需要將您的return移動到函數結束,否則將不會執行它下面的臺詞:

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; 
}