繁体   English   中英

PHP-CODEIGNITER如何在会话中获取数据

[英]PHP-CODEIGNITER how to get data in session

我想回显我的旅行清单,当我尝试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中显示。

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视图。

更新资料

尝试遍历数组之前检查数组是否为空,例如在您的视图中:

<?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;
}
?>

改变你的模型

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();

您不能回显数组的内容。

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

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

我看不到您的代码有任何问题。 如果您没有使用自动加载器加载会话库 ,则可能是您的问题:

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

您可以查看文档Codeigniter会话

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM