簡體   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