【问题标题】:PHP-CODEIGNITER how to get data in sessionPHP-CODEIGNITER如何在会话中获取数据
【发布时间】:2017-09-29 10:47:30
【问题描述】:

我想回显我的行程列表,当我尝试 print_r 时,值可以显示,但当我总是回显结果时

消息:未定义变量:冒险

文件名:views/profile.php

行号:121

回溯:

严重性:警告

消息:为 foreach() 提供的参数无效

文件名:views/profile.php

行号:121

这是我的控制器:

 public function getListTrip(){         
    $this->load->model('userModel');        
    $data['adventure'] = $this->userModel->getTrip()->result_array();
    //echo ($data);
    $this->load->view('profile', $data);        
 }

这是我的模型:

function getTrip(){
    $userId = $this->session->userdata('user_id');    
    return $this->db->get_where('adventure',['user_id' => $userId]);
}

这是我的看法

                        <table>
                           <?php
                            foreach ($adventure as $b){
                                echo "<tr>
                                <td>$b->name</td>
                                <td>$b->place</td>
                                <td>$b->category</td>

                                </tr>";
                            }

                        ?>
                        </table>

那么我应该如何编辑我的代码以使值显示在我的页面中,而 echoforeach 不在 print_r 中...非常感谢

【问题讨论】:

标签: php codeigniter session


【解决方案1】:

改变你的模型

function getTrip(){
    $userId = $this->session->userdata('user_id');    
    $query= $this->db->get_where('adventure',['user_id' => $userId]);
    return $query->result();
}

也在你的控制器中改变

$data['adventure'] = $this->userModel->getTrip()->result_array();

$data['adventure'] = $this->userModel->getTrip();

【讨论】:

  • 它的工作老兄,谢谢.. 但鉴于我的控制器 /getListTrip 在我的 /profile 中看不到,我应该看到这个
【解决方案2】:

echo 用于输出一个或多个字符串,因为您的$data 是一个数组,您会看到错误,您需要将数据传递给视图并在视图本身中对其进行迭代,例如:

public function getListTrip(){
    $this->load->model('userModel');
    $data['adventure'] = $this->userModel->getTrip()->result_array();
    //pass data to your view
    $this->load->view('yourviewname', $data);
}

更多信息请查看Codeigniter Views

更新

在尝试遍历它之前检查您的数组是否不为空,就像在您的视图中一样::

<?php
if( !empty($adventure) ) {
    foreach($adventure as $b):
?>
        <tr>
            <td><?php echo $b['name']; ?></td>
            <td><?php echo $b['place']; ?></td>
            <td><?php echo $b['category']; ?></td>
        </tr>
<?php
    endforeach;
}
?>

【讨论】:

  • 我尝试了您的建议,但在我的视图页面中仍然出现一些错误,请帮助我我的错误在哪里??
  • @FahmiSalmin 检查添加的代码。顺便说一句,由于结果是数组,因此您无法使用 '->' 运算符访问字段。
【解决方案3】:

您不能回显数组的内容。

因此,每当您想查看数组的内容时,请使用 print_r($arrayName);

当您只想打印任何变量时,只需使用echo $variableName;

【讨论】:

    【解决方案4】:

    我认为您的代码没有任何问题。如果您没有使用自动加载器来加载可能是您的问题的会话库

    $this->load->library('session');
    

    您可以查看文档Codeigniter sessions

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2017-04-13
      • 2016-07-03
      • 2016-05-28
      • 2013-07-07
      相关资源
      最近更新 更多