2011-04-13 5 views
1

나는이두 테이블을 하나의 테이블에있는 자동 성가신 ID와 연결하는 방법은 무엇입니까?

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

같은 테이블과 다른 테이블이있는 경우

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

은 내가 COL1의 값을 삽입하고 id_attrib을 COL2하는 자동 증가로 테이블 tbl_attributes에 값을 삽입하는 시간이 온다 . 어떻게 테이블 tbl_weight의 id_attrib 필드에 동일한 자동 증분 값 id_attribute를 삽입 할 수 있습니까? 그 이유는 tbl_attributes에 특정 값이 입력되고 찾고자하는 값이 tbl_attributes에 삽입되면 그와 관련된 더 많은 정보가 tbl_weight에 입력되기 때문입니다.

그렇지 않으면 난 빈 데이터 많이 포함됩니다

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

필드 열 같을 것이다 뭔가가 충족되고 난 그런 식으로 그것을하고 싶지 않는 경우에만 데이터를 포함 할 테이블을 결합합니다.

그래서 현재 auto_increment가 tbl_attributes에 사용되고 그 값을 삽입 할 수 있습니다. 나는 innodb 형식을 사용하려고 생각하고 있었지만 나는 그 세계에 익숙하지 않았으며 일들이 엉망이 될 수도 있습니다.

답변

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

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

수동 : mysql_insert_id()

이전 하여 AUTO_INCREMENT 컬럼에 대해 생성 된 ID를 가져옵니다 쿼리 (일반적으로 INSERT).

이제 다른 INSERT 쿼리 (tbl_weight)에 해당 ID를 사용할 수 있습니다.

예 :

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

참고 : mysql_query() 결과를 확인하는 것을 잊지 마십시오.

+0

나는 목적을 보지 못하기 때문에 결코 쿼리 결과를 확인하지 않습니다. 그게 무슨 목적 이니? thnx –

+0

결과 확인의 목적은 무엇입니까? 요청이 성공했는지 확인하려면? 예 : mysql_query ('잘못된 MySQL 요청')'... 그러면 오류가 발생합니다. – Wh1T3h4Ck5

2

첫 번째 자동 증가 표에 삽입 한 후 PHP 함수 mysql_insert_id()을 호출하십시오. 그러면 이전 삽입에서 자동 증가 ID가 리턴되며, 이후 삽입에서 사용할 수 있습니다. PHP 함수에 의해 호출 네이티브 MySQL의 기능에 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입니다 mysql_insert_id()

관련 문제