0

I'm trying to build a site with codeigniter and when a user logs in I am able to get the email address they logged in with from the sessions data so I therefore can pin point their record which is in the database.

At the moment I am only able to get these records by querying the database where $email = email blah blah and doing a foreach statement which isn't ideal. I would rather be able to get the users id via the email address which has been passed in the sessions. Then pass the id into the urls for each item of the navigation menu when they log in and get the content this way.

Not sure if I'm being clear but what I need help with is:

  1. Get the correct record from the database based on the session email

  2. Creating dynamic URLs which pass the users id into each item of the navigation menu once logged in

  3. Display that users content based on the id which is in the url

I have this for the function in my controller at the moment:

$email = $this->session->userdata('email');
$query = $this->db->get_where('users', array('email' => $email));

    foreach($query->result_array() as $result){
        echo $result['id'];
    }

So I'm unsure of what I need to do, getting muddled up, any help is greatly appreciated!

AyeTry
  • 75
  • 3
  • 12
  • Are you allowing multiple users to use the same email address? – Brett DeWoody Jul 30 '13 at 19:42
  • @BrettDeWoody No all users will register and log in different email address. You also won't be able to register if you're email address is already in the database so the email is unique to the user. – AyeTry Jul 30 '13 at 19:44
  • Ah, I see. So your query always returns a single row. Correct? – Brett DeWoody Jul 30 '13 at 19:55
  • @BrettDeWoody Yeah that's right but I want a better way to do it if possible. – AyeTry Jul 30 '13 at 19:56
  • in terms of your overall goals would suggest you consider using randomly generated string or 'token' instead of user email or user id. – cartalot Jul 30 '13 at 23:32

1 Answers1

0

Since you're expecting a single row you can use $query->row_array().

$email = $this->session->userdata('email');
$query = $this->db->get_where('users', array('email' => $email));

$user = $query->row_array();

echo $user['id'];

More info on generating query results on the CodeIgniter docs.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • To answer the rest of your question, you could then save the `$user['id']` into a session variable to you don't have to pass it around in the URL. – Brett DeWoody Jul 30 '13 at 20:02