views:

96

answers:

2

I am trying to implement a rating system where I keep the following two fields in my db table:

rating (the current rating) num_rates (the number of ratings submitted so far)

UPDATE mytable SET rating=((rating*num_rates)+$theRating)/num_rates, num_rates=num_rates+1 WHERE uniqueCol='$uniqueCol'

the variables are from my PHP code.

So, basically sometimes the row with the uniqueCol does not exist in the DB, so how can I do the above statement if the exists and if it doesn't then do something like this:

INSERT INTO mytable rating=$theRating, num_rates=1, uniqueCol=$uniqueCol

+2  A: 

Have a look at INSERT ... ON DUPLICATE KEY UPDATE.

It should look something like that:

INSERT INTO mytable (rating, num_rates, uniqueCol)
VALUES ($theRating, 1, $uniqueCol)
ON DUPLICATE KEY UPDATE
  rating=((rating*num_rates)+$theRating)/num_rates,
  num_rates=num_rates+1;

Make sure to have a UNIQUE index or PRIMARY KEY on your uniqueCol.

Peter Lang
A: 

I use this mysql_affected_rows

link : http://nl2.php.net/manual/en/function.mysql-affected-rows.php

Grumpy