在cakephp中插入数据

时间:2015-12-29 06:14:14

标签: php mysql cakephp cakephp-2.x

我有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个字段存储到数据库中。我的代码有什么问题。?

2 个答案:

答案 0 :(得分:2)

使用

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

而不是

Invitefriend->save() 

答案 1 :(得分: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);
    }
}