2012-03-14 37 views
0

最後一條記錄使用這個PHP代碼:獲取在MySQL

try{ 
    $dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // INSERT CLEAN DATA INTO TABLE… 
    $sth = $dbh->prepare(" 
    INSERT INTO Fan(fanNm,fanEmail,fanPass,fanDynamSalt) 
    VALUES('$userName','$userEmailAddress','$userPassword','$dynamSalt')" 
    ); 
    $sth->execute(); 
    //////////////////////////////////////////////////////////////////// 
    ## Set Session Var for this PK ID in Fan table that is being created ## 
    //////////////////////////////////////////////////////////////////// 
    $_SESSION['newUserSessID'] = mysql_insert_id(); 
    echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>"; 
} //try 

catch(PDOException $e){ 
     echo "Oops, We're experiencing an error."; 
     file_put_contents('/PDODBConnectionErrors.txt', $e->getMessage(), FILE_APPEND); 
} //catch 

它插入FINE到數據庫中,但我使用echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>";呼應的是,值,它始終返回零。

即使我運行:

SELECT LAST_INSERT_ID() 
FROM Fan 
LIMIT 0 , 30 

它給我像

0 
0 

輸出(因爲在數據庫表中兩行)

有人嗎?

+1

mysql_insert_id()檢索先前查詢爲AUTO_INCREMENT列生成的ID。您的任何欄目是否爲AUTO_INCREMENTS?範的其他領域是什麼? – 2012-03-14 01:56:07

+0

HTML標籤需要雙引號('''),而不是單引號('''),你在'echo'語句中有。 – Jon 2012-03-14 01:57:09

+0

@AmitBhargava - 是的PK是自動增量。 – CodeTalk 2012-03-14 01:58:22

回答

3

您不應該使用mysql_insert_id,因爲這不是PDO的一部分(在這種情況下,您正在使用它來與數據庫進行交互)。

而是使用PDO::lastInsertId()

$_SESSION['newUserSessID'] = $dbh->lastInsertId(); 

更多信息:http://www.php.net/manual/en/pdo.lastinsertid.php

+0

heh,打我吧 – Flukey 2012-03-14 02:00:05

+0

完美,抱歉PDO很新,很簡單。謝謝@Ezequiel Muns! – CodeTalk 2012-03-14 02:01:35

0

你正在與通用MySQL功能混合PDO。問題是mysql_last_insert沒有資源,所以它返回false爲false。請勿混用PDO與通用MySQL功能。

要獲得PDO最後插入的ID,這樣做: $dbh->lastInsertId()

http://php.net/manual/en/pdo.lastinsertid.php