Welcome Guest, Not a member yet? Register   Sign In
Inserting into related tables simultaneously
#1

[eluser]NetChaos[/eluser]
In a website I’m developing, for user registration I have two tables, “users” table and “users_info” table with the following sample fields.
Quote:"users" table -> "id (primary key, auto increment), username, password, created_on" etc

Quote:"users_info" table -> "id (primary key, auto increment), users_id, first_name, last_name, billing address, shipping address" etc.
The "users_id" field in the "users_info" table is to set relationship between the tables. (Database engine is MYISAM not INNODB)
Using this I know how to select, update and delete the records from both table but wondering how to insert a new record to both tables simultaneously using active records or otherwise.
In the user guide I saw the "$this->db->insert_id()" function. Will it be a fool proof method to get the "id" using "$this->db->insert_id()", after inserting to the "users" table and use it as the "users_id" while inserting into the "users_info" table ?

Thank You
#2

[eluser]Twisted1919[/eluser]
Code:
if(! $this->db->insert('table1',$info))
{
return FALSE;
}
$user_id = $this->db->insert_id():
$info2['user_id'] = $user_id ;
return $this->db->insert('table2',$info2);
Smile
#3

[eluser]NetChaos[/eluser]
Thanks for the reply.
One more help, can I do it from the same model or do I have to create separate models for each table to stick to the MVC architecture ?
#4

[eluser]Twisted1919[/eluser]
same model of course .
#5

[eluser]NetChaos[/eluser]
@Twisted1919 Thanks for the help
#6

[eluser]jedd[/eluser]
Hi NetChaos,

You could probably solve your problem more easily by normalising your schema - all the fields you mentioned there should go into one table.

If you continue with your current approach you should remove the auto-increment attribute on one of the table's primary keys.




Theme © iAndrew 2016 - Forum software by © MyBB