-4

I have a table named product where there is a field named id its the primary key here. I need to put this key to my another table pro_size_tbl as below

pro_size_tbl 
==================
id
productid
sizeid

the matter is when the user adds a product the sizes of the products are saved in session and I am trying to save them in pro_size_tbl by the product key what I just made.

The thing I am doing right now is I am adding the product in the product table and in the next line I am retrieving the max id of the product table and using it as the key for the pro_size_tbl.
My question is is there any better way to do this thing?

शेखर
  • 17,412
  • 13
  • 61
  • 117
  • possible duplicate of [Get the id of inserted row using C#](http://stackoverflow.com/questions/405910/get-the-id-of-inserted-row-using-c-sharp) – omgitsfletch Feb 03 '14 at 04:59

4 Answers4

2

This is simple.You can use LAST_INSERT_ID().See this sample:

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
SET @last_id_in_table1 = LAST_INSERT_ID();
1

There is a function LAST_INSERT_ID() which can give you the desired value.

But you need to use right below the insert statement.

शेखर
  • 17,412
  • 13
  • 61
  • 117
0

owh. from what i understood, u need to put auto generated mysql id to another table?

if so, here is the real deal

$sql_tbl1 = "insert here for first table";
$result_tbl1 = mysql_query($sql_tbl1) or die(mysql_error());

$id = mysql_insert_id();

$sql_tbl2 = "insert here value ($id, 'bla', 'bla')";
mysql_query(sql_tbl2);
0

LAST_INSERT_ID() function is ok but it is doing the same work as i am doing taking the maximum value.i guess more or less both way are the same.