函数返回假阴性

时间:2012-06-04 00:42:18

标签: php

我在MySql数据库中保存游戏状态。信息已成功保存,但它回应说保存游戏状态时出错。我还在调整到php,不知道它来自哪里。

PS我知道SQL语句是不安全的。现在我只是在基本面上升并运行,因为语句和表格本身很快就会改变。

列入传入的json:

    } else if ($tag == 'save_game_state') {
    $email = $_POST['email'];
    $virtumon = $_POST['monster'];
    $qty = $_POST['qty'];
    $exp = $_POST['exp'];
    $user = $db->saveGameState($email, $monster, $qty, $exp);
        if ($user) {
            $response["success"] = 1;
            $response["The game state has been successfully saved"];
         echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = 1;
            $response["error_msg"] = "Error occured in saving the game state";
            echo json_encode($response);
        }

将信息输入数据库并返回成功/失败。

    public function saveGameState($email, $monster, $qty, $exp) {

    $result = mysql_query("INSERT INTO user_profiles(email, monster, qty, exp) VALUES('$email', '$monster', '$qty', '$exp')") or die(mysql_error());
    // TODO check for successful store
    $success = mysql_query("SELECT email, monster, qty, exp FROM user_profiles WHERE email = '$email' AND monster= '$monster' AND qty = '$qty' AND exp = '$exp'");
   if ($success) {
            return mysql_fetch_array($success);
    } else {
       return false;
   }
}

2 个答案:

答案 0 :(得分:3)

绝对不应该在SELECT之后运行INSERT来查看它是否有效。只需检查$result运行后的内容。来自

来自http://php.net/manual/en/function.mysql-query.php

  

对于其他类型的SQL语句,INSERT,UPDATE,DELETE,DROP等,mysql_query()成功时返回TRUE,错误时返回FALSE

尝试

$result = mysql_query("INSERT INTO user_profiles(email, monster, qty, exp) VALUES('$email', '$monster', '$qty', '$exp')") or die(mysql_error());
return $result;

如果要返回刚刚插入的内容,请在运行saveGameState后调用另一个函数。但是,如果您已经拥有这些值,则可以使用这些值而不是再次查询数据库。

您还应该考虑使用PDO

答案 1 :(得分:1)

您正在检查您的select语句是否成功。您应该检查插入是否成功。

if ($result = mysql_query(INSERT INTO user_profiles(email, monster, qty, exp) VALUES('$email', '$monster', '$qty', '$exp') or die(mysql_error())) {
    if ($success = mysql_query("SELECT email, monster, qty, exp FROM user_profiles WHERE email = '$email' AND monster= '$monster' AND qty = '$qty' AND exp = '$exp'") or die(mysql_error())) {
        if (mysql_num_rows($success) > 0) return mysql_fetch_assoc($success);
    }
}
else { return false; }