Skip to content Skip to sidebar Skip to footer

How To Send Data To Two Tables With Same User Id As Primary Key?

I am totally new to PHP and I'm trying to create a registration page. To register, a user has to create a username, password, email, which are put into a table called users. They

Solution 1:

Before anything, you should not use mysql_* extension anymore. Go towards PDO or mysqli


Your technique generates two different unique ids. The point is to have only one, so that it can be unique, and link information on that unique id.

The users table is the one with that unique id, user_id, which is your auto_increment column. The customer_info table can also have a info_id unique column, but must contain a user_id column, which will contain the user's user_id, linking the rows together.

It would also be a great moment to add a foreign key to your tables so that integrity of the data won't be compromised.

so after this query:

$result = mysql_query(
    "INSERT INTO `users`(username, password, email) VALUES ('$value1', '$value2','$value3')"
);

get the insert id:

$id = mysql_insert_id();

then run your other query with it:

$result = mysql_query(
    "INSERT INTO `customer_info`(user_id,firstname, lastname, b_add_num, b_add_road, b_add_town, b_add_pc, p_add_num, p_add_road, p_add_town, p_add_pc) VALUES ('$id','$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13')"
);

Solution 2:

I would configure USER_ID as an AUTO_INCREMENT column only in Users table, insert the data into Users table first, then get the ID of the user inserted, using the mysql_insert_id ($connection_id); and use that while inserting data into Customer_Info table. This way, you can leverage the ID generation (sequence) feature of MySQL as well.

Post a Comment for "How To Send Data To Two Tables With Same User Id As Primary Key?"