Welcome Guest, Not a member yet? Register   Sign In
Frequently used function, where to store
#1

[eluser]avramovic[/eluser]
Ok, first of all, I am new with CI, and I have looked at documentation but haven't found answer to my question: I am using function "getusernamefromid" because I have ID of user stored in database table, and I need username of that user very often. The function is something like this:

Code:
function getuserfromid($id) {
  $this->db->where('id',$id);
  $query = $this->db->get('users',1);
  $row = $query->result();
  return $row[0]->username;
}

Now, this helper functions are usually defined as functions in helper files, but every helper I saw is NOT using database. I need to connect to database and get username, and when I place this code in helper file (and load helper) it says that I can not use that (function getuserfromid is not defined in class so I can't use $this)... so... how can I achieve this?
#2

[eluser]Michael Wales[/eluser]
Place it within a Model.
#3

[eluser]xwero[/eluser]
Instead of accessing the db every time you need to display the username you could store the username in a session variable.

For your question if you want to use functions throughout your site create your own library, put it in the application/libraries directory and autoload it. Your library could be like this

Code:
class Mine
{
function getuserfromid($id) {
  $this->db->where('id',$id);
  $query = $this->db->get('users',1);
  $row = $query->result();
  return $row[0]->username;
}
}

To call it following line will do if you autoload it

Code:
$this->Mine->getuserfromid($id);
#4

[eluser]avramovic[/eluser]
Yes, but I am not getting username of currently logged user. Smile

@walesmd: Ah, that's it. It works. Thank you

It seems that I haven't looked at that part of manual after all. Big Grin




Theme © iAndrew 2016 - Forum software by © MyBB