繁体   English   中英

CodeIgniter在Controller或Model中加载数据库?

[英]CodeIgniter load database in Controller or Model?

型号:

class Users_model extends CI_Model {
    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function get_all_users() {
        return $this->db->get('users');
    }
}

控制器:

class Users extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('security');
        $this->load->model('Users_model');
    }

    public function index() {
        redirect('users/view_users');
    }

    public function view_users() {
        $data['query'] = $this->Users_model->get_all_users();
        $this->load->view('users/view_all_users', $data);
    }
}

我的问题是我应该把$ this-> load->数据库放在哪里? 在模型或构造函数中? 如果可能的话告诉我原因? 还有一个问题, 如果我省略了$ this-> load->数据库则会显示错误

“未定义的属性:Users :: $ db”。 我期待“未定义的属性:Users_model :: $ db”。

这是为什么? 它是在控制器还是模型中寻找$ db? 谢谢。 注意:我可以很好地连接到数据库。 实际上我问的是,如果我想使用$ this-> load-> database()。 我应该把它放在哪里? 控制器或型号? 为什么?

转到autoload.phpapplication/config/autoload.php ,并添加此

$autoload['libraries'] = array('database'); // add database in array(now you dont need to load database at anywhere in project)

使数据库连接设置database.php ,位于文件application/config/database.php

现在尝试这个

 class Users_model extends CI_Model {
  function __construct() {
    parent::__construct();
    //$this->load->database(); <----remove this
  }

  public function get_all_users() {
    return $this->db->get('users');
  }
}

您可以在控制器中加载数据库,也可以在模型中加载它。

数据库中的所有交互都在模型中,而控制器是连接视图和模型的人,所以它的整洁和干净并没有多大区别。

这里的控制器就像买方和卖方之间的中间人。

在控制器中加载数据库

<?php 
   class Test_controller extends CI_Controller {

        public function __construct()
      {
          parent::__construct();
          $this->load->database('default');
          $this->load->model('test_model');
      }

      public function index()
      {
        $this->db->from('test');
        $query = $this->db->get();
        echo "<title>CodeIgniter SQlite</title>";
        $data['db']=$query->result();
        //print_r($data['db']);
        $count = count($data['db']);
        echo "Row count: $count rows<br>";
        for ($i=0; $i < $count; $i++) { 
          echo $data['db'][$i]->text." ";
        }
      }
   }
?>

在模型中加载数据库

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test_model extends CI_Model
{

    public $table1 = 'test';
    public $table2 = '';



    public function __construct()
    {
        parent::__construct();
        $this->load->database('default');
    }

    public function check_db()
    {
        $this->db->from($this->table1);
        $query = $this->db->get();
        return $query->result();
    }
}

暂无
暂无

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

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