2015-06-04 51 views
0

我想上傳一個圖像到數據庫,並將值id,markerID(字符串,非唯一),imagename(文本),註釋(文本)和喜歡(int)添加到我的表接線板。在數據庫中插入值自動增加ID

這是我的PHP Scirpt:

if (isset($_POST["image"]) && isset($_POST["markerID"])) { 
    $data = $_POST["image"]; 
    $markerID = $_POST["markerID"]; 
    $ImageName = $id.".png"; 
    $filePath = "CEimages/".$ImageName; 
    echo "file ".$filePath; 

    if (file_exists($filePath)) { 
     unlink($filePath); //delete old file 
    } 

    $myfile = fopen($filePath, "w") or die("Unable to open file!"); 
    file_put_contents($filePath, base64_decode($data)); 

    //id, markerId, image, note, likes 
    mysql_query("INSERT INTO pinboard VALUES ('', '{$markerID}', '{$ImageName}', '', '')") or die ('Could not save entry: '.mysql_error()); 
} 

的問題是我設置$ ImageName。我希望ImageName等於該ID,因此它是唯一的。但是,稍後設置id時,我添加了值(id是自動增量)。 如何將ImageName設置爲ID,如果該行在同一個腳本中被插入?

+0

如果圖片的名字和id一樣,爲什麼還要存放它呢? – Augwa

+0

'$ ImageName = $ id。「。png」;'做什麼? – Alex

回答

3

用了形象的名字第一次插入記錄不是更新映像路徑後

讓你的最後一個ID mysql_insert_id();

+0

謝謝,新代碼: 'if(isset($ _ POST [「image」])){ \t $ data = $ _POST [「image」]; \t $ markerID = $ _POST [「markerID」]; (「','{$ markerID}','','','')」);}注意: \t $ id = mysql_insert_id(); \t $ ImageName = $ id。「。png」; \t $ filePath =「CEimages /".$ ImageName; \t echo「file」。$ filePath; \t if(file_exists($ filePath)){ \t \t unlink($ filePath); \t} \t $ myfile = fopen($ filePath,「w」); \t file_put_contents($ filePath,base64_decode($ data)); \t mysql_query(「UPDATE pinboard SET image ='$ ImageName'WHERE id ='$ id'」); }' – maidi

0

你可以插入查詢之前,使用mysql_insert_id()最後插入的ID,然後你可以增加它和保存它作爲圖像名稱。

但是,如果您的應用程序一次運行多個操作,這不是理想的方法。

此外,你應該使用mysqli或PDO而不是mysql。

相關問題