Codeigniter选择2个用户并向他们发送电子邮件

时间:2016-01-24 16:03:20

标签: codeigniter codeigniter-2

当我使用以下代码发送电子邮件时,它可以正常工作。

public function select() {
$this->load->library('email', array('mailtype' => 'html'));
                $this->email->from('test@test.com','abc');
                $this->email->to('test1@test.com');
                $this->email->subject('test subject');
                $message = "Hello";
                $this->email->message($message);
                if($this->email->send()) {
                    $data["msg"] = "Email has been successfully sent.";
                    $this->load->view("view_test", $data);
                }
                else {
                    $data["msg"] = "Email sending failed.";
                    $this->load->view("view_test", $data);
                }
}

但是当我想按ID选择2个用户然后发送电子邮件时它不起作用。你可以查看我下面的代码并帮我找出我的错误。

型号

public function did_select() {
        $this->db->select('email, name');
        $this->db->from('users');
        $this->db->where('user_id', 5);
        $this->db->where('user_id', 11);
        $query = $this->db->get();
        if ($query && $query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return false;
        }
}

控制器:

public function select() {
      if ($this->model_admin->did_select()) {
          foreach ($query->result_array() as $row)          {
              $name = $row['name'];
              $email = $row['email'];
                $this->load->library('email', array('mailtype' => 'html'));
                $this->email->from('test@test.com','abc');
                $this->email->to($email);
                $this->email->subject($name.'test subject');
                $message = "Hello";
                $this->email->message($message);

                if($this->email->send()) {
                    $data["msg"] = "Email has been sucessfully sent.";
                    $this->load->view("view_test", $data);
                }
                else {
                    $data["msg"] = "Email sending failed.";
                    $this->load->view("view_test", $data);
                }
              }
            }
}

2 个答案:

答案 0 :(得分:0)

问题是这两行

    $this->db->where('user_id', 5);
    $this->db->where('user_id', 11);

这会产生类似

的查询
Where user_id=5 and user_id=11

这不是你想要的。所以你应该用

替换第二行
    $this->db->or_where('user_id', 11);     

也许您应该删除foreach循环之外的视图加载。

答案 1 :(得分:0)

您已在模型中返回result_array,因此无需加倍。在控制器中尝试下一步:

if ($this->model_admin->did_select())
{
    $mails = $this->model_admin->did_select();
    foreach ($mails as $row)
    {