2015-12-29 45 views
0

我有5個輸入框,當用戶填寫的5個領域,並擊中提交,我們需要存儲的數據庫插入數據

爲此,我有這樣的代碼在我的控制器

public function send() 
{ 
$this->loadmodel('Invitefriend'); 
$this->request->is('post'); 
$this->Invitefriend->create(); 
$this->loadModel('Student'); 
$id = $this->userValue['Student']['id']; 
$contact = $this->userValue['Student']['phone']; 
$emails= $this->data['Invitefriends']; 
$currentDate=date('Y-m-d',strtotime($this->currentDate)); 
$email_count = count($emails); 
for($i=1;$i<=$email_count;$i++) 
{ 
$email = $emails['email'.$i]; 
$this->Invitefriend->save(array("ref_student_id"=>$id, "ref_contact"=>$contact, 'email'=>$email, 'date'=>$currentDate)); 
} 
} 

與只將最後一個字段值插入到數據庫中,但我需要將所有5個字段存儲到數據庫中。在我的代碼中是否有任何錯誤?

回答

1

使用

// save multiple or all records 
$this->Invitefriend->saveAll() 
or 
$this->Invitefriend->saveMany() 

,而不是

Invitefriend->save() 
0

試試這個:

//Create entity for table... 
$invTable = $this->Invitefriend->newEntity(); 

//Build db table fields... 
$invTable->ref_student_id = $id; 
$invTable->ref_contact = $contact; 
$invTable->email = $email; 
$invTable->date = $currentDate; 

//Store data into table... 
$this->Invitefriend->save($invTable); 

你的功能如下所示:

public function send() { 
    $this->loadmodel('Invitefriend'); 
    $this->request->is('post'); 
    $this->Invitefriend->create(); 
    $this->loadModel('Student'); 
    $id = $this->userValue['Student']['id']; 
    $contact = $this->userValue['Student']['phone']; 
    $emails= $this->data['Invitefriends']; 
    $currentDate=date('Y-m-d',strtotime($this->currentDate)); 
    $email_count = count($emails); 

    //Create entity for table... 
    $invTable = $this->Invitefriend->newEntity(); 

    //Build db table fields... 
    $invTable->ref_student_id = $id; 
    $invTable->ref_contact = $contact; 
    $invTable->date = $currentDate; 

    for($i=1;$i<=$email_count;$i++) { 

     $invTable->email = $emails['email'.$i]; 

     //Store data into table... 
     $this->Invitefriend->save($invTable); 
    } 
}