2015-12-01 28 views
1

我想設置一個變量的值爲在插入我的查詢之前插入到DB 中的最後一個ID。設置查詢前的最後一個ID的值

目前我有以下代碼:

// Construct 
public function __construct($content, $emotion, $conn) 
{ 
    $this->content = $content; 
    $this->emotion = $emotion; 
    $this->post = 
     "<div id=\'post\'> 
      <div id=\'postContent\'> 
       <p><b>I\'m $this->emotion because</b> $this->Id $this->content<span class=\'emot\'id=\'$this->emotion\'></span></p> 
      </div> 
      <div id=\'postInfo\'> 
       <span class=\'postRelate\' title=\'Click to relate +1\'><p><b>relate</b> (0)</p></span> 
       <span class=\'postSubmitted\'><p>submitted X minutes ago</p></span> 
      </div> 
     </div>";  
} 

// Confirm booking (update database) function 
public function insert_userPost($conn) 
{ 
    if($this->content != "") 
    { 
     // SQL INSERT command 
     $sql = ("INSERT INTO userPost (content, submitted, emotion) 
       VALUES ('$this->post', NOW(), '$this->emotion')"); 
     $this->Id = $conn->insert_id; 
     if ($conn->query($sql) === TRUE) 
     { 
      header('Location: feed.php?filter=all&page=1'); 
     } 
     else 
     { 
      echo "Error: " . $sql . "<br>" . $conn->error; 
     } 
    } 
    else 
    { 
     header('Location: post.php'); 
    } 
} 

在構建我設置變量$後含含$這個 - > id變量一個div。

向下insert_userPost()函數我插入一個包含$ this-> post的查詢,另一個將Id設置爲插入到數據庫中的最後一個ID。我知道它已經成功從數據庫中獲取ID了。但是,由於我明確獲得Id 之前的值,因此insert在插入後不能正確顯示在$ post上。

+0

在將數據庫實際插入到數據庫中之前,您無法獲取數據庫的內部標識符...您可能會從先前插入的行中獲取標識符! –

+0

是的,我沒有把它說得很好。我的問題更多的是關於如何實現相同的目標。我有什麼可以做的嗎?我知道我可以從數據庫和+1中獲得最高的ID,但我可以想象這會導致一些非常討厭的問題。 –

+0

@LiamMacmillan:是的它會..沒有正確的方法來獲得最後插入的ID除了實際插入最後一行和檢索其ID。 – D4V1D

回答

0

除非確實插入一行,否則無法從數據庫獲取ID。很難預測MySQL使用的是什麼ID。

您必須在構造中添加帖子以獲取ID以供參考。您可以將數據庫中的新列設置爲posted=falsesubmitted=NOW()

IN insert_userPost()您設置了posted=true並刪除了所有與posted=false WHERE submitted<DATE_SUB(NOW(), INTERVAL -1 DAY)的行。

另一種解決方案是將所有內容暫時存儲在不帶ID的會話變量中,並存儲/讀取會話中的更改。當它發佈時,將它添加到數據庫中!

相關問題