开发者

how to link two table with a auto incrimented id in one table?

if i have a table like this

tbl_attributes
---------------
id_attrib (auto incremented, primary key)
col1
col2

and another table

tbl_weight
--------------
id_attrib *(not primary key)*
field

when it comes time to insert values into the table tbl_attributes as i insert values for col1 and col2 the id_attrib is auto incremented. how can i insert that same auto incremented value of id_attribute into the field id_attrib in the table tbl_weight . the reas开发者_如何转开发on im doing this is because i am looking for specific values being entered into tbl_attributes and once the value im looking for has been inserted into tbl_attributes then more information related to that will be entered into tbl_weight.

otherwise if i combined the tables which would look like

tbl_attributes
----------------
id_attrib
col1
col2
field (from tbl_weight table)

the field column would contain alot of empty data and would only contain data when something is met and i dont want to do it like that.

so maybe getting the current auto_increment to be used for tbl_attributes and insert that value. I was thinking of using innodb format but i am new to that world and things might get messed up.


$sql = "INSERT INTO tbl_attributes VALUES(...)";
$res = mysql_query($sql);

if ($res) {
  $last_autoincrement_id = mysql_insert_id();
  // add code here
  }

Manual: mysql_insert_id()

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

Now you can use that ID for another INSERT query (tbl_weight).

Example:

$sql = "INSERT INTO tbl_weight VALUES('$last_autoincrement_id', ...)";
mysql_query($sql);

Note: Don't forget to check mysql_query() result.


After inserting into the first auto increment table, call the php function mysql_insert_id(). This will return the auto increment id from the previous insert, which you can use in your subsequent insert. The native MySQL function called by the PHP function is LAST_INSERT_ID()

$result = mysql_query("INSERT INTO tbl_attributes (col1, col2) VALUES ('val1', 'val2');");

if ($result)
{
   // Get the auto increment id from the first INSERT
   $last_id = mysql_insert_id();
   // And use it in the second INSERT
   $result2 = mysql_query("INSERT INTO tbl_weight (id_attrib, field) VALUES ($last_id, 'fieldval');");
}
else // first insert failed

Official PHP documentation on mysql_insert_id()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜