2011-03-16 96 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; 
}