我正在做一个Flex/Php项目。我已经写了这个php脚本,如果一个艺术家还没有在数据库中,我插入他并将like_score置为1。如果他已经存在,我们通过添加+1来更新like_score。这是我到目前为止所得到的:
// Variables
$php_artist = $_POST["rma_artist"];
/*
* A simple query to know if the artist exists in the DB by its name. We can't use id since we won't get that value.
* if $numrows > 0, we have a match. We calculate the number of likes and then, we update.
* else, we insert.
*/
$query = "SELECT like_score FROM rma_likelist WHERE like_artist = '$php_artist'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$numrows = mysql_num_rows($result);
// UPDATE if there is a row that matches, we update
if ($numrows > 0) {
$newLikeScore = $row["like_score"] + 1;
$query = "UPDATE rma_likelist SET like_score = '$newLikeScore' like_artist = $php_artist";
if ( !mysql_query($query, $mysql_connection) ){
die('ERROR: '. mysql_error() );
}
// id, name, likes, operation
$response = $php_artist_id.":::".$php_artist.":::".$newLikeScore.":::MYSQL UPDATE SUCCESSFULL";
}
// INSERT if no rows match, we insert a new record
else {
$query = "INSERT INTO rma_likelist (like_artist, like_score) VALUES ('$php_artist', '1')";
$message = "INSERT SUCCESSFULL, 1 Record Added";
if ( !mysql_query($query, $mysql_connection) ){
die('ERROR: '. mysql_error() );
}
$new_id = mysql_insert_id();
// id, name, likes, operation
$response = $new_id.":::".$php_artist.":::1:::MYSQL INSERT SUCCESSFULL";
}
echo $response;
?>(或参见pastebin:http://pastebin.com/HwHYXaGP)
它几乎是有效的:如果一个艺术家还没有在数据库中,它会插入它,并给它一个like_score为1。它还会识别一个艺术家是否已经在数据库中,因为它不会复制任何艺术家。然而,它永远不会更新数据库中已经存在的波段的like_score,它总是保持1。为什么会发生这种情况?我已经找了很久了=/
发布于 2011-12-18 09:37:19
您的代码可能无法工作,因为您的UPDATE语句不完整:
$query = "UPDATE rma_likelist SET like_score = '$newLikeScore'
/* missing WHERE keyword */ like_artist = $php_artist";该语句应包含... WHERE like_artist = ...
我本以为您的错误会导致语法错误,但我看到您正在检查来自mysql_query()的错误结果,所以我不确定您为什么没有检测到它。
另外,如果$php_artist是一个字符串,那么在UPDATE语句中没有引用它。
您还应小心创建SQL injection漏洞。
也就是说,我建议您可以通过使用INSERT... ON DUPLICATE KEY UPDATE大大简化您的代码。
$query = "INSERT INTO rma_likelist (like_artist, like_score) VALUES (?, 1)
ON DUPLICATE KEY UPDATE like_score = like_score + 1";
$stmt = $pdo->prepare($query);
$stmt->execute( array($php_artist) );PS:如上所述,我也会使用带有查询参数的PDO,而不是过时的ext/mysql。
发布于 2011-12-18 08:40:43
我想like_score会在$row
在更新查询$query = "UPDATE rma_likelist SET like_score = '$newLikeScore‘WHERE like_artist =$php_artist“中缺少where;
在这些情况下,最好的做法是让like_artist具有唯一性,并使用mysql的on duplicate key update特性。
发布于 2011-12-18 08:21:15
你应该使用MERGE来做你想做的事情:
MERGE into rma_likelist using (select pk_artist_id from rma_likelist where pk_artist_id = theid)
when not matched then insert into rma_likelist values (...)
when matched then update rma_likelist set like_score = like_score + 1 where ...(查询不完整是不是你的脚本中有些部分我不理解)
这里的明显优势是,您甚至不需要查询来检查艺术家的存在--少了一个bug来源;)
https://stackoverflow.com/questions/8548934
复制相似问题