Search code examples
model-view-controllercodeigniter-4

how to fetch the MySQL data and use it on the controller in CODEIGNITER


Model and Controller Image I am facing the data from the database as an array and now I want to access the data in the same Controller method. Is it possible? suppose my MODEL is (method name attendance)

$query = $this->db->query("SELECT emp_name FROM attendance WHERE id= '1' ");
        $result = $query->getResult('array');

My controller:

$data["emp_info"]=$this->userdata->attendance();
        return view("addleave_v",$data);

So in the controller, I have fetched the data and stored it on $data['emp_info'] it is a single element array. So I want to use the emp_name in the controller. How can I use it? I tried emp_info['emp_name], $data['emp_info']['emp_name'] I have used an image attachment. Thanks


Solution

  • I recommend you to see the library Result Arrays and Result Rows.

    Based on the data you provided (var_dump)

    array(1) { [0]=> array(10) { ["uiid"]=> string(2) "30" ["attendance_date"]=> string(10) "2021-03-09" ["emp_id"]=> string(1) "9" ["time_in"]=> string(19) "0000-00-00 00:00:00" ["time_out"]=> string(19) "0000-00-00 00:00:00" ["comments"]=> string(14) "APPROVED LEAVE" ["overtime"]=> string(1) "0" ["status1"]=> string(1) "1" ["created_by"]=> string(0) "" ["total_time"]=> string(0) "" } }

    1. Your array is structured as a multi-element array. You can view the current data using a loop (foreach) or refer to the first element of an array (in controller $data["emp_info"][0]['emp_name'] or in view $emp_info[0]['emp_name']).
    2. If you need a single-element array, use getRowArray() or getRow('array'). Then you will be able to use the variables as you first wanted.
    • in controller $data["emp_info"]['emp_name']
    • in view $emp_info['emp_name]