2014-12-12 3 views
-1

데이터가 존재하는지 여부를 확인하고 싶습니다. 데이터가 있으면 "user_star_rate"테이블을 업데이트하고, 그렇지 않으면 데이터를 테이블에 삽입하십시오. 삽입이 제대로 작동하지만 업데이트가 작동하지 않습니다.존재하는 경우 업데이트하는 방법, 그렇지 않으면 PHP에 삽입 하시겠습니까?

여기 내 코드입니다.

$jsqla7 = mysql_query("select * from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error()); 
$jfeta7 = mysql_fetch_assoc($jsqla7); 

if($jfeta7 != null) { 
    $rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ; 
} else { 
    $rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ; 
} 
+1

사용하지 않는 = null이!. mysql_num_rows 또는 count를 사용하십시오. –

+0

mysql_fetch_assoc는 반환 할 행이 없을 때 NULL이 아닌'FALSE'를 리턴합니다. – axiac

+1

** mysql_ * 함수를 사용하지 마십시오. mysql 확장은 향후 제공되지 않을 예정이며 향후 삭제 될 예정입니다. mysqli 또는 PDO를 사용하십시오. – axiac

답변

1

내가 당신의 말, 당신은 정말 replace into를 사용되어야하고, 그것은 또한 크게 코드를 줄일 것 이해합니다.

코드는 될 것입니다 :

$query = "REPLACE INTO user_star_rate(product_id, email) VALUES('$product_id', '$visit_email')"; 
mysql_query($query) or die(mysql_error()); 

이미 다음이 업데이트됩니다 존재하는 경우, 다른 사람이 삽입됩니다. 외래 키 및 자동 증가 ID와 관련하여 문서에 특히주의해야합니다.

1

이 시도 :

$tot = mysql_num_rows($jfeta7); 
if($tot > 0){ 
    $rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ; 
} else { 
    $rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ; 
} 
1

시도 :

이 이
 $jsqla7 = mysql_query("select count(*) from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error()); 
     $count = mysql_num_rows(); 

     if($count) { 
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ; 


     } else { 
      $rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ; 
     } 
관련 문제