Welcome Guest, Not a member yet? Register   Sign In
Ideal way for user information storing in cms and working with it
#1

[eluser]Michal1[/eluser]
Hello guys,

I have been working on simple cms to make my codeigniter skills better. I have two tables in database.

First is "articles" which contains fields "id" "title" "text" "user_id"

Second is table "users" which contains fields "id" "name"

What I do is that I have simple controller which handles displaying articles and also adding articles. Users can log in using session class and add their own articles. Now what I want to do is to store their id and use it in controller which handles article displaying so I can show who is the author of that article.

So in the controller which handles adding articles I have something like

Code:
public function add_post()
{
  $data = array(
  'title' =>$this->input->post('title'),
                'text' =>$this->input->post('text'),
  );
  
  $this->site_model->insert_post($data);
  
  redirect ('site');

And I need to get that user_id as well. I know how to do that by using session class. And so I will only add another field to data array so it will look something like:

Code:
$data = array(
  'title' =>$this->input->post('title'),
                'text' =>$this->input->post('text'),
                'user_id'=>  make some operations with session to get id of user who added article
  );

But that does not solve my problem because it will save only user_id. While I need save name of the users as well. So of course I can create another field in that array call user_name and then pass it there from session again but it seems kinda like piggy approach for me. Because my thinking is that once I have that user_id stored in "articles" table I can somehow compare it with "id" from table "users" probably in model and somehow get that user_name. Does anybody know how to do that and most importantly is this the right approach?

Thank you very much


#2

[eluser]Samus[/eluser]
Yeah.

I had to do this several times.

I simply created a model which looked a little like this.

Code:
class User extends CI_Model {

function id_to_name($id) {
$query = $this->db->get_where('user_table', array('id' => $id));
$q = $query->row();
return $q->username;
}

}

Now all you have to do is call it in your controller.

Code:
$username = $this->user->id_to_user($this->session->userdata('id'));

That's a bland example, you can do whatever checks you want to ensure the user id exists, but it won't be necessary if your authentication is setup right.




Theme © iAndrew 2016 - Forum software by © MyBB