2015-05-09 48 views
0

您好,所以我有一個表,名爲tblcontactlist,並有5列(使用ContactID名稱,聯繫人姓名,contactEmail,contactNumber,hashed_id),這是我工作的查詢PDO lastInsertId在同一個查詢

$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber) VALUES (:cname, :cea, :cnum)"; 
     $stmt = $dbc->prepare($query); 
     $stmt->bindParam(':cname', $contactName); 
     $stmt->bindParam(':cea', $emailAdd); 
     $stmt->bindParam(':cnum', $contactNumber); 
     $stmt->execute(); 

     $last_id = $dbc->lastInsertId('contactID'); 
     $hashed_id = sha1($last_id); 

$query2 = "UPDATE tblcontactlist SET hashed_id=:hid WHERE contactID=:cid"; 
     $stmt2 = $dbc->prepare($query2); 
     $stmt2->bindParam(':hid', $hashed_id); 
     $stmt2->bindParam(':cid', $last_id); 
     $stmt2->execute(); 

這是什麼基本上沒有被插入新記錄,然後使用hashed_id列上的散列ID更新最新插入的記錄。有沒有適當的方法來做到這一點?我的意思是代碼更短或代碼更好。謝謝!

+0

手段旁邊插入要轉換它更新?或插入後,你想獲得最後插入的ID,然後做一些更新的東西? –

+0

插入記錄時,hashed_id也會更新並插入,而不執行更新查詢。那可能嗎? – FewFlyBy

+0

不能理解抱歉。通過在代碼中評論來指出你的問題。 –

回答

1

lastInsertId前提是你有一個以前的INSERT事先,你沒有。在這種情況下,lastInsertId是最大contactID。所以我會執行一個查詢來獲取並散列最大contactID,然後執行一個插入查詢(並且不更新)。

//fetch Max contactID 
    $res=$dbc->prepare("SELECT MAX(contactID) FROM tblcontactlist");  
    $res->execute();   
    $fetchMax=$res->fetch(PDO::FETCH_NUM); 

    $last_id=$fetchMax[0]; 
//hash the max contactID 
    $hashed_id = sha1($last_id); 
    //for reusability you can create a function with the above code. 

現在執行插入查詢:

$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber, hashed_id) VALUES (:cname, :cea, :cnum, :hid)";    
      $stmt = $dbc->prepare($query);  
      $stmt->bindParam(':cname', $contactName); 
      $stmt->bindParam(':cea', $emailAdd); 
      $stmt->bindParam(':cnum', $contactNumber); 
      $stmt->bindParam(':hid', $hashed_id); 
      $stmt->execute(); 

是更好的嗎?

+1

感謝您的幫助,但我已經使用更新查詢。和你的行$ res-> execute($ params);應該是$ res-> execute();只有:D – FewFlyBy

+0

謝謝,正確。我已經在我的核心類系統上使用綁定參數實現了maxid函數,所以我有一個參數數組的$參數。 –

+0

再次感謝主席:) – FewFlyBy