模型如何在 Codeigniter 中保存来自控制器的数据

How model can save data from controller in Codeigniter

我有一个网络应用程序需要向许多人发送消息friends.But我遇到了一个错误..请帮助我....

下面是我的控制器

public function message(){

$this->form_validation->set_rules('message','Message', 'required');
$this->form_validation->set_rules('friend_id[]','Recipients', 'required');
if($this->form_validation->run()){
     $data = $this->input->post("friend_id[]");
    unset($data['submit']);
    $this->load->model('Queries');
    $message=$this->Queries->saveMessage();
    if($message){
    echo "Success";
    }else{
    echo "error";
    }

     }
     else{ 
     echo validation_errors();
        }
     }

这是我的模型

 public function saveMessage($data){
     $i=0;
     foreach($data['friend_id'] as $friend_id){

          $record = array(
          'friend_id' => $friend_id,
          'message' => $data['message']
          );
          $this->db->insert('tbl_messages', $record);
          $i++;
             }
              return $data;
          }

当我 运行 它..它显示错误并且没有数据插入数据库

希望对您有所帮助:

你的控制器方法message()应该是这样的:

public function message()
{
    $this->form_validation->set_rules('message','Message', 'required');
    $this->form_validation->set_rules('friend_id[]','Recipients', 'required');
    if($this->form_validation->run())
    {
        $friend_ids = $this->input->post("friend_id[]");
        $message = $this->input->post("message");
        unset($data['submit']);
        $this->load->model('Queries');
        $insert = $this->Queries->saveMessage($friend_ids, $message);
        if($insert)
        {
            echo "Success";
        }
        else
        {
            echo "error";
        }
     }
     else
    { 
     echo validation_errors();
    }
}

你的模型方法saveMassage()应该是这样的:

public function saveMessage($friend_ids , $message)
{
    foreach($friend_ids as $friend_id)
    {
        $record = array('friend_id' => $friend_id,'message' => $message);
        $this->db->insert('tbl_messages', $record);
    }
    return true;
}