Welcome Guest, Not a member yet? Register   Sign In
In view check if there is rows in the database
#1

[eluser]WebbHelp[/eluser]
Hi!

I am pretty new with codeIgniter and I just started a project.
My question is just about right or wrong.

In my view file:
If there is rows in the database THEN show a form, if not, don't show the form...
When I will see if there is rows in the database... Shall I do it right into the view file?
Or shall I first create a model-function which return the rows to the controller, and from the controller... yes what am I supposed to do?

I want to learn this in the correct way!

Can you please tell me what I am "Allowed" to write in the view file and what I should put in the controller class instead.

I understand that all view content will be in the view files, but what PHP am I allowed to write in the view file?

Thanks
#2

[eluser]InsiteFX[/eluser]
The correct way is to use the num_rows() in your model!
Code:
public function get_post($id)
{
    $data = array();

    $this->db->where('id', $id);
    $this->db->limit(1);
    $query = $this->db->get('posts');

    if ($query->num_rows() > 0)
    {
        // Return the data
        $data = $query->row_array();
        return $data;
    }
    else
    {
        // No data return FALSE
        return FALSE;
    }
}

InsiteFX
#3

[eluser]WebbHelp[/eluser]
This do the same, is this correct?

My model:
Code:
public function count_menu()
    {
        return $this->db->count_all('menu');
    }

and then the controller:
Code:
public function index()
    {
        $this->load->library('easyform');
        
        $this->load->model('site_model');
        
        $data['count_menu'] = $this->site_model->count_menu();
        $data['get_menu'] = $this->site_model->get_menu();
        $this->load->view('header');
        $this->load->view('left_menu');
        $this->load->view('admin/menu_admin_view', $data);
        $this->load->view('footer');
    }

and then the view:
Code:
if($count_menu > 0)
{
//dodododo
}
#4

[eluser]Ted S[/eluser]
Whoops, missed your model code at a glance. Ignore the previous post please!

count_all() will fetch the number of rows but also creates a second query. If you're just checking to see that there are rows before looping through them in your view, run one query and use the function num_rows() first.

Code:
if($XXXXX->num_rows() > 0){
....
}

If you have a larger plan, like using the total of a large table but only showing a handful of results, then you may need both queries.




Theme © iAndrew 2016 - Forum software by © MyBB