aries
aries

Reputation: 64

How to check if there are values in a table in the database in CodeIgniter

I'm creating a project where in I want to verify if there is a data that has been inserted in a table by a certain user and display it if there's any. I'm fairly new to CodeIgniter and I'm unsure of how to display all the lists that has been by a certain user if it is logged in.

This is what I have in my model so far:

 public function get_all_lists($user_id){
            $this->db->where('list_creator_id', $user_id);
            $query = $this->db->get('lists');

            return $query->result();    
        }

This is what I have on my view:

<li class="list-group-item">
                <a href="<?php echo base_url();?>project_controllers/lists/create" class="btn btn-success pull-right">
                    Create a List
                </a>
                <h3 align="center">
                    <a href="<?php echo base_url();?>project_controllers/lists/display/<?php echo $list->id;?>">
                        <?php echo $list->list_name; ?>
                    </a>            
                </h3>
            </li>
        <?php endforeach; ?>

And this is what I have on my controller:

public function index(){
        $user_id = $this->session->userdata('user_id');
        $this->load->model('project_models/lists_model');

        $data['lists'] = $this->lists_model->get_all_lists($user_id);

        $data['main_view'] = "project_views/lists/index";

        $this->load->view('project_views/layouts/main', $data);
    }

My goal here is to display all the lists that has been created by a certain user if it is logged in. If the user has been logged in and has not created any list, I want a message that says, "You don't have created any lists yet".

Upvotes: 0

Views: 769

Answers (1)

Alex
Alex

Reputation: 9265

Use num_rows() to return either the object or false.

public function get_all_lists($user_id){
            $this->db->where('list_creator_id', $user_id);
            $query = $this->db->get('lists');
            if ($query->num_rows() > 0) {
                return $query->result(); 
            }
            return false;
        }

Usage:

if ($lists) {
    foreach(...) {

    }
} else {
    echo 'no rows';
}

Upvotes: 1

Related Questions