duanjia7607 2016-01-26 17:33
浏览 42
已采纳

CodeIgniter将模型数据传递给视图[重复]

This question already has an answer here:

I have a model method which returns time and view to pass the data. But when I pass the data I get Undefined variable error message.

$this->load->model('Driver_model');
$result = $this->Driver_model->get_shift_data($id);

This is the method calling and if I use var_dump($result). I get following result.

array (size=1)
  0 => 
    object(stdClass)[26]
      public 'start_time' => string '2016-01-22 05:32:42' (length=19)

But if I send the $result to the view, I get error.

$this->load->view('driver/report_view.php', $result);

My question is, how it possible to work in controller if I don't load the view. But if I send the data, it doesn't identify the variable.

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: result

Filename: driver/report_view.php

Line Number: 52

Backtrace:

File: C:\wamp\www\cabs\application\views\drivereport_view.php
Line: 52
Function: _error_handler

File: C:\wamp\www\cabs\application\controllers\Driver.php
Line: 44
Function: view

File: C:\wamp\www\cabs\index.php
Line: 292
Function: require_once

I have tested it using var_dump($result) in view as well.

      <div class="panel-body">
Line 52    <?php var_dump($result); ?>                              
        <form>
</div>
  • 写回答

1条回答 默认 最新

  • dongtan6695 2016-01-26 17:47
    关注

    You can not pass a simple variable $result in load view function for view.

    You need to create an associative array for sending data to view from controller. You can use as:

    $this->load->model('Driver_model'); $data['result'] = $this->Driver_model->get_shift_data($id);
    

    Now send $data array to your view as:

    $this->load->view('driver/report_view.php', $data);
    

    Now you can use var_dump() in view file as:

    <?php var_dump($result); ?>
    

    Note that if you want to send any other data from controller to view you can follow the same example.

    For more explanation see this example:

    $data['result'] = 1;
    $data['result2'] = 2;
    $data['result3'] = 3;
    
    $this->load->view('yourview', $data);
    

    In view you can get data as:

    echo $result; // 1
    echo $result2; // 2
    echo $result3; // 3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启