• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is this how to insert a foreign key?

Hey all!
So I'm pretty new to CodeIgniter (and back-end coding in general). So this is my first question!

Ok so below is some code I made that will look at the id of a user when he logs in and save it to a session.

Then in the second part I insert form data into another table and match the foreign key's id to that of the user by looking at the value I saved in the session.

I'm not sure if I'm doing this right (even though it does seem to work). So I'd just like to check if there is by chance an easier/better way or if this is right...

To be honest I'm not sure if my approach is right at all. So here's the code...

First I get the user's id when he logs in and save it to a session like this...
if ($query)//if the user's credentials validated we create the session...
//look up currently logged in studio's id and save it to $studio_id
$get_studio_id = $this->db->get_where('studio', array('email' => $this->input->post('username')));
if ($get_studio_id->num_rows() > 0)
  $row = $query->row();
  $studio_id = $row->id;

[color=gray]//create array for session and set_userdata[/color]
$data = array(
  'username' => $this->input->post('username'),
  'is_logged_in' => TRUE,
  'studio_id' => $studio_id


Then through my controller I call on this model when submitting a form, which inserts the form's values into my table (while pulling the parent id from the session and setting it as the foreign key)...
class Families_model extends CI_Model {

public function create_family()
  $studio_id = $this->session->userdata('studio_id');

  $new_family_insert_data = array(
   //table name => data to insert
   'parent1' => $this->input->post('parent_1'),
   'parent2' => $this->input->post('parent_2'),
   'phone' => $this->input->post('phone'),
   'email' => $this->input->post('email'),
   'street' => $this->input->post('street'),
   'city' => $this->input->post('city'),
   'state' => $this->input->post('state'),
   'zip' => $this->input->post('zip'),
   'emergency_name' => $this->input->post('emergency_contact'),
   'emergency_phone' => $this->input->post('emergency_phone'),
   'password' => md5($this->input->post('password')),
   'studio_id' => $studio_id

  $insert = $this->db->insert('family', $new_family_insert_data);
  return $insert;



Whatcha think? Smile

Am I even approaching it right?

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.