2011-03-16 32 views
0

我想插入一些文章。我想先做個裁判,如果圖像值已經在數據庫中,插入一個空值。 詳細解釋: 如果有這些數據:php mysql插入(當有東西重複時,插入一個空值)

title1,image1 
title2,image2 //this is image2 first appear, so insert it 
title3,image2 //image2 has already in the database, so insert an empty value for just image field 
title4 
title5,image3 

最終數據插入到數據庫應該是這樣的:

title | image 
title1,image1 
title2,image2 
title3 
title4 
title5,image3 

這裏是我的代碼,但它仍然插入重複值成數據庫。那麼有沒有人可以幫助我?謝謝。

foreach{//first here has a foreach to make all the articles as a queue 
... 
if(!empty($image)){ //first judge if the insert article had a image value 
$query1 = mysql_query("select * from articles where .image = '".$image."' "); 
while ($row = mysql_fetch_array($query1)) { 
$image1 = $row['image']; 
} 
} 
if(!empty($image1)){ //make a query first if the image has already in the database 
    mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','' "); 
}else{ 
    mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','".$image."' ");; 
} 
} 

回答

0

您的第一個查詢中包含錯誤。您必須刪除「圖像」之前的點:

where **.**image 
+0

權,一些寫入錯誤......它傳遞,而工作,我是這麼認爲的。 – cj333 2011-03-16 11:57:39

0

正如Francesco所說,點可能是該查詢的問題。

不太清楚你在這裏要做什麼。但是,如果你是想阻止相同的圖像文件被存儲然後兩次,你應該使用類似下面這樣:

function is_same_file($image1, $image2){ 

    if(filesize($image1) != filesize($image2) 
     return false; 

    if(hash_file('md5', $image1) != hash_file('md5', $image2)) 
     return false; 

    return true; 
}