【问题标题】:setting session in foreach loop in codeigniter在codeigniter的foreach循环中设置会话
【发布时间】:2013-06-11 07:08:21
【问题描述】:

我在 codeigniter 中有一个模型,它使用 foreach 循环从数据库获取通知。我想使用 set_userdata 将值传递给会话,但不幸的是我无法将多个值传递给我的会话,请帮助。下面是我的模型

function get_user_notifications($userID){
               $this->db->select()->from('messages')->where('receiverID',$userID);   
                $query = $this->db->get();
                if($query->num_rows()>0)
     {
            foreach($query->result() as $rows)
        {
          //add all data to session

            $notification=$rows->notification;
            $messageID=$rows->messageID;
            // $rows->messageID =>,



      $this->session->set_userdata('mynotifications',$notification);
        }


     }

【问题讨论】:

  • 你遇到了什么错误?
  • 您必须在您实际要访问会话值的每个页面上启动会话。

标签: php codeigniter loops session foreach


【解决方案1】:

将所有通知添加到您在 foreach 之前实例化的数组中,然后将该数组添加到会话中。

另请注意,如果您使用标准的 codeigniter 会话,则其大小有 4k 限制,因此这可能不是最佳方法。

此外,这是假设您的会话类已正确初始化...

我已尽力清理您的代码。

function get_user_notifications($userID){
    $this->db->select()->from('messages')->where('receiverID',$userID);   
    $query = $this->db->get();
    $all_notifications = array();
    if($query->num_rows()>0)
    {
          foreach($query->result() as $rows)
          {
           //add all data to session
               $all_notification[]=$rows->notification;
               $messageID=$rows->messageID;     

          }
          $this->session->set_userdata('mynotifications',$all_notification);
    }

【讨论】:

  • 感谢一百万人,这是我第一次发帖,我很感激你有多么有帮助 n ths thng z :-)
【解决方案2】:

试试这个,

function get_user_notifications($userID){
    $this->db->select()->from('messages')->where('receiverID',$userID);   
    $query = $this->db->get();
    $notification='';
    if($query->num_rows()>0)
    {
        foreach($query->result() as $rows)
        {
            //add all data to session
            $notification.=$rows->notification.',';
            $messageID=$rows->messageID;
            // $rows->messageID =>,
        }
    }
    $this->session->set_userdata('mynotifications',$notification);
}

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 2015-03-07
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多