phparrayscodeignitermodel-view-controllerresultset

How to set up a CodeIgniter MVC structure to retrieve 0 or 1 row from the database and present the data in the view file


I need help do get some data from array that is forwarded to my view. In my controller's method I was load model who returns me data array from db, and than I pass that data to my view, and that looks like this:

function deleteAccount($data){
    $this->load->model('model_admin');
    $dataFromModel = array();
    if ($query = $this->model_admin->retrieveAccount ($data)) {
        $dataFromModel['records'] = $query;
        $this->load->view('admin/test', $dataFromModel);
    }  else {
        echo "No data was returned";
    }
}

and in my view I manage to retrieve that data and to echo it like this:

<?php
echo "TEST page<br/>";

if (isset($records)) {
    foreach ($records as $row) {
        echo $row->username;    
    }
} else {
    echo "No data";
}
?>

But I am certain that if I retrieve data from db it is either one line or no lines at all, so in my view page I would like to echo that data without foreach loop on some way, for example like this:

echo $records->username;

or:

echo $records[0]; //because it is the first argument in line

but in both ways it throws an error :

1 - first case: Trying to get property of non-object

2 - second case: Object of class stdClass could not be converted to string

This is my model:

function retrieveAccount($data)
{ 
    $query = $this->db->get_where('table_users', array('username' => $data[2]));
    return $query->result();
}

Can someone help me, and show me how to retrieve that data?


Solution

    1. If you want to use $records->username this means $records must contain only one value. In this case instead of using $query->result(), use $query->row() in your model code.

    2. You cannot echo stdClass object. $records[0] is stdClass object thus Php is giving this error. Instead this would work

      echo $records[0]->username