查询(mysql)应该只在$ sqltext< $ _ POST [评分]

时间:2011-12-19 10:32:41

标签: mysql

我有以下查询:

$sqltext = "SELECT Score FROM HighScore ".
    "WHERE fbID='$_POST[fbID]' AND ".
        "Layout='$_POST[Layout]'";
$result = mysql_query($sqltext); 

if(mysql_num_rows($result)>0){
    $sql = "UPDATE HighScore SET Score = '$_POST[Score]', ".
        "Time = '$_POST[Time]', ".
        "Stars = '$_POST[Stars]' ".
        "WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'"; 
} else {
    $sql = "INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) ".
        "VALUES ('$_POST[fbID]','$_POST[Layout]',".
        "'$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}

它做什么?那么它会检查数据库中是否有行(总是只有1行或没有行)。如果没有行,则在数据库中插入一个新行。如果该行存在,它将更新该行。一切正常。

$ sqltext将给出一个值。该值可以是234,3424342或甚至-392。如果此值小于'$ _POST [Score]'值,则应更新该行。目前它没有,我似乎无法正常工作。那么我怎么能这样做,如果$ sqltext(这是从db得分)< '$ _POST [得分]'它应该更新行而忽略它? (也没有插入)。

2 个答案:

答案 0 :(得分:1)

您还可以在UNIQUE KEY上添加(fbID, Layout)约束,然后只使用一个查询:

$sql = "
     INSERT INTO HighScore 
       (fbID, Layout, Score, Time, Stars) 
     VALUES ( '$_POST[fbID]', '$_POST[Layout]'
            , '$_POST[Score]', '$_POST[Time]', '$_POST[Stars]'
            )
     ON DUPLICATE KEY 
     UPDATE
           Score = GREATEST(Score, VALUES(Score))
         , Time = VALUES(Time)
         , Stars = VALUES(Stars)
       ";

答案 1 :(得分:0)

$sqltext= "SELECT Score FROM HighScore WHERE fbID='$_POST[fbID]'AND Layout='$_POST[Layout]'"; $result = mysql_query($sqltext); 

if(mysql_num_rows($result)>0){
  if ($row = mysql_fetch_assoc($result))
  {
    if ($row['Score'] < $_POST['Score'])
    {
            $sql="UPDATE HighScore SET Score = '$_POST[Score]', Time = '$_POST[Time]', Stars = '$_POST[Stars]' WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'"; 
    }
  }
}else{
            $sql="INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) VALUES ('$_POST[fbID]','$_POST[Layout]','$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}

我认为这就是你想要的。但它没有做任何事情,如果有一行并且得分高于POST中的得分['得分']