-1

I want to check whether the data is existing or not. If data exists, update the table called "user_star_rate", otherwise insert the data into the table. Inserting is working properly, but the updating is not working.

Here is my code.

$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')" ;
}
Amare
  • 685
  • 2
  • 8
  • 22
  • 1
    do not use != null. Use mysql_num_rows or count – Marco Mura Dec 12 '14 at 08:50
  • `mysql_fetch_assoc` returns `FALSE`, not `NULL` when there is no row to return. – axiac Dec 12 '14 at 08:52
  • 1
    **DO NOT** use the `mysql_*` functions. The `mysql` extension is deprecated and will be removed in the future. Use `mysqli` or `PDO`. – axiac Dec 12 '14 at 08:53
  • You can use mysql to handle this ... take a look here http://stackoverflow.com/questions/4205181/insert-to-table-or-update-if-exists-mysql – donald123 Dec 12 '14 at 08:54

3 Answers3

1

Try this :

$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')" ;
}
Alex
  • 626
  • 7
  • 16
1

If I understand what your saying, you should really be using a replace into and it would also decrease your code significantly.

Your code would become:

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

If it already exists then it will update it, else it will insert it. You should pay special attention to the docs in regards to foreign keys and auto incrementing ids.

Ne Ma
  • 1,719
  • 13
  • 19
1

Try:

     $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')" ;
        }