douzhuang6321 2017-09-04 21:25
浏览 55
已采纳

无法在php函数中运行db查询

I have created a function in my views and have tried to make a query within the php function but i do not know I am getting and unexpected error which was never been seen in my entire career can anyone help me out to get rid from this error?

Severity: Error --> Using $this when not in object context /application/views/includes/create_calendar.php 51

This is my controller

class Booking extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array("form", "url"));
        $this->load->library('session');
        $this->load->database();
    }

    public function get_calendar() {
        $this->load->view('includes/create_calendar');
    }
}

This is the file in which I am trying to run a query views/includes/create_calendar.php

function getCalender($year = '',$month = '') {  
   $sql       = $this->db->get('calendar');
   if($day == $sql->row()->day_off) { $per_off = $sql->row()->per_off; }

                        echo "<p>".$day." Off</p>";
}
  • 写回答

1条回答 默认 最新

  • donglian7879 2017-09-04 21:27
    关注

    In CodeIgniter usage, if you need to use one of the classes that is available in the "super object", you must first get an instance of the super object:

    $CI =& get_instance();
    $CI->db->get('calendar');
    

    This DB class may not even be loaded. If that's the case, then before you use db:

    $CI->load->database();
    

    To clarify, as soon as you go in that function, you've removed $this from the variable scope, like this simple test:

    class Test {
    
        public $foo = 'bar';
    
        public function index() {
            function baz(){
                return $this->foo;
            }
            echo baz();
        }
    }
    
    $t = new Test;
    $t->index();
    

    You could do something like the following, but that's really messy:

    class Test {
    
        public $foo = 'bar';
    
        public function index() {
            function baz($x) {
                return $x->foo;
            }
            echo baz($this);
        }
    }
    
    $t = new Test;
    $t->index();
    

    The best thing for you to do is find another cleaner way to do what you are doing. You wouldn't normally want calls to your database and functions in your views. It goes against what MVC is all about.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理