CodeIgniter Forums
Got empty results from model, even though there're data in database - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Got empty results from model, even though there're data in database (/showthread.php?tid=1527)



Got empty results from model, even though there're data in database - gabrielpasv - 03-18-2015

Hi Guys,

I am new to codeIgniter and I have a problem when working with models.

Database is setup fine and has some fake data on the table. However I can't access then.

My model
PHP Code:
class Site_model extends CI_Model {

    function 
getAll() {
        
$data = array();
        
$q $this->db->get('test');
        if (
$q->num_rows() > 0) {

            foreach (
$q->result() as $row) {
                
$data[] = $row;
            }
        }
        return 
$data;
    } 


My Controller
PHP Code:
class Site extends CI_Controller {

    public function 
__construct() {
        
parent::__construct();
    }

    public function 
index() {
        
$this->load->model('site_model');
        
$data['records'] = $this->site_model->getAll();
        
$this->load->view('home'$data);
        echo 
$data['records'];
    }




My View
PHP Code:
<html>
    <
head>
        <
title>title</title>
    </
head>
    <
body>
        <
div id="container">
            <
p>My View has been loaded</p>
        </
div>
        <
pre>
            <?
php print_r($records?>
        </pre>
    </body>
</html> 


And here is the results I got ( An empty array )

My View has been loaded

Array
(
)


RE: Got empty results from model, even though there're data in database - RobertSF - 03-18-2015

Hi Gabriel, the problem is that you're not loading the database in Codeigniter. You need a line that says $this->load->database(); You can put that line in three places:

1.- In your application/config/autoload.php file.
2.- In the function where you access the database.
3.- In the constructor of your model file.

Personally, I prefer to put it in the constructor of my model files. If you put it in your autoload file, it will load on every single page. If you put it in the function that accesses the database, you'll have to include it in every function that accesses the database. But if you put it in the model file, then the database only gets loaded in controllers where you load that model file. So in your model file, you can do something like this.
PHP Code:
class Site_model extends CI_Model {

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

 
   function getAll() {
 
       $data = array();
 
       $q $this->db->get('test');
 
       if ($q->num_rows() > 0) { 
That should do it.

Also, I figured you would have gotten an error message. Do you have errors turned on in your PHP.INI file?