2011-12-26 94 views
1

請考慮一個名爲foo的表,其中有id (PRIMARY & AUTO_INCREMENT)列。我在這張桌上插入一行,挑戰從這一點開始。依賴於「mysql_insert_id」

$db->query("INSERT INTO `foo` (id, row1, ...) VALUES('', '$row1', ...)"); 
if (!$db->is_error && $db->last_insert_id) { 
    $id = $db->last_insert_id; 
    do_really_important_things_with_last_ID($id); 
    do_another_important_things_with_last_ID($id); 
    ... 
    do_ ... with_last_ID($id); 
    do_ ... with_last_ID($id); 
} 

我插入查詢後立即調用它,並使用完全相同當前連接鏈路,而越來越last_insert_id,但不知道怎麼做的事情(?)。

$this->dbh = @mysql_connect(.....); 
... 
// query function 
$this->result = @mysql_query($query, $this->dbh); 
... 
if (preg_match("/insert/i", $query)) { 
    $this->last_insert_id = @mysql_insert_id($this->dbh); 
} 


我應該擔心這個實現依賴於mysql_insert_id

回答

5

LAST_INSERT_ID應該是一個函數,將返回插入的ID

function last_insert_id(){ 
return @mysql_insert_id(); 
} 

if (!$db->is_error && $db->last_insert_id()) { 
    $id = $db->last_insert_id(); 
    do_really_important_things_with_last_ID($id); 
    do_another_important_things_with_last_ID($id); 
    ... 
    do_ ... with_last_ID($id); 
    do_ ... with_last_ID($id); 
} 
+0

Thanks @Hemant;但是,如果$ query包含'INSERT'關鍵字「,那麼我會立即在$ db-> query()'function」中存儲'$ this-> last_insert_id'。 – 2011-12-26 10:53:08

+0

通過在查詢中跳過使用id字段來嘗試 – Dau 2011-12-26 10:55:00

4

http://dev.mysql.com/doc/refman/5.1/en/getting-unique-id.html更多的信息,所以這樣說:

「對於LAST_INSERT_ID(),最近生成的在每個連接的基礎上,服務器的ID號保持在 ,不會被另一個 客戶端更改,如果您更新另一個AUTO_INCREMENT 列, onmagic值(也就是說,值不是NULL,並且不是0)。同時使用來自多個客戶端的LAST_INSERT_ID()和AUTO_INCREMENT列 完全有效。每個客戶端 將獲得最後插入的ID的最後聲明,客戶 執行。」

所以你應該罰款做你想要什麼,你不應該奇怪的結果。