[英]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. 我正在使用mysql_affected_rows()来检查是否必须输入新记录或更新现有记录,但是问题是用户是否尝试输入与已插入的记录完全相同的数据。
$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 ('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')");
what should i do to avoid redundant entries 我应该怎么做以避免重复输入
mysql_info()
output (but the solution itself will be affected by race condition issue) 您可以解析mysql_info()
输出(但解决方案本身将受到竞争条件问题的影响) You could create unique key User + Date
and end up with a single query using ON DUPLICATE KEY UPDATE syntax: 您可以创建唯一键User + Date
并使用ON DUPLICATE KEY UPDATE语法以单个查询结束:
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: 一些解决方案:
i'd go with first option. 我会选择第一个。
btw, you should escape your post data (mysql_real_escape_string) to prevent injects or malformed query string 顺便说一句,您应该转义您的发布数据(mysql_real_escape_string)以防止注入或格式错误的查询字符串
You may get the number of affected rows with FOUND_ROWS()
instead of mysql_affected_rows()
. 您可以使用FOUND_ROWS()
而不是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 参考: http : //dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.