mitch2k mitch2k - 5 months ago 13
PHP Question

Get db value from within controller in array

I'm trying to get a value from the database inside a controller like this:

//Load model
$this->load->model('files/files_model');

//Lookup file
$file = $this->files_model->findfilebyid('1');

echo "Filepath: " . $file->filepath . "<br>";
echo "Filename: " . $file->filename . "<br>";


But when I do this, I get a "Trying to get property of non-object" error. I Also tried $file->['filepath'] and $file[0]->filepath, but this does not work.

Printing the array with 'print_r(array_values($file))' gives this:

Array ( [0] => stdClass Object ( [fileid] => 1 [filenamefriendly] => Kiosk manual [filename] => kiosks [filenamepath] => filestorage [fileownerid] => 4 [filepermissiontype] => global [filepermissioncompanyid] => 0 [filecategoryid] => 1 [filecreatedate] => 2015-11-20 00:00:00 [filedescription] => This is the manual of the kiosks [filetype] => pdf ) )


Am I trying to put an array in an array or something? How can I access the values?

Answer

That's because you're returning a full result set (which is an array of objects) While what you actually wants is a single object since the 'id' should be a primary key.

In your findfilebyid it should be something like:

public function findfilebyid ($id) {
       $q = $this->db->where('id', $id)->get('files');
       return $q->row();
}
Comments