开发者

mysql_affected_rows(); does not work for checking if row exists

i am using mysql_affected_rows() to check if i have to enter new record or update existing, but the problem is if the user tries to enter exactly same data as record which already exists it runs insert into.

$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_affected_rows();

if ($last==0) {

    $result1 = mysql_query("INSERT INTO Data (User,Date,Score,Comment) VALUES ('$_P开发者_JAVA技巧OST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')");

what should i do to avoid redundant entries


  1. You could parse mysql_info() output (but the solution itself will be affected by race condition issue)
  2. You could create unique key User + Date and end up with a single query using ON DUPLICATE KEY UPDATE syntax:

    INSERT INTO `Data` (User,Date,Score,Comment)
    ('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')
    ON DUPLICATE KEY UPDATE Score='$score',Comment='$_POST[Comments]'
    


some solutions:

  1. add another query to see if data exists, and then decide if you want to do some action (update/delete) or nothing.
  2. add a 'modified' column with type "TIMESTAMP" and make it on update - CURRENT_TIMESTAMP

i'd go with first option.

btw, you should escape your post data (mysql_real_escape_string) to prevent injects or malformed query string


You may get the number of affected rows with FOUND_ROWS() instead of mysql_affected_rows(). The latter counts the not modified rows as well.

$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_query("SELECT ROW_COUNT();");
$last = mysql_fetch_array($last);
...

Reference: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜