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.

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

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题