使用php / mysql检查和扣除点数

时间:2016-11-24 08:34:55

标签: php mysql

对于天才来说,这可能是一个非常简单的问题。我试图使用PHP代码来检查我的数据库,看看用户是否有足够的积分。然后,如果他们有足够的积分,那么从那里扣除积分。 这就是我目前使用的不起作用的地方:

<?php
    $con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
    $response = array();
    $statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
    mysqli_stmt_bind_param($statement, "s", $_POST["username"]);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $userID, $name, $username, $password, $points);
    $pointsint = (int)$points;

    if ($pointsint > 12500){
        $statement = mysqli_prepare($con, "UPDATE user SET points = points - ? WHERE username = ?");
        mysqli_stmt_bind_param($statement, "is", 12500, $_POST["username"]);
        mysqli_stmt_execute($statement);

        mysqli_stmt_store_result($statement);
        mysqli_stmt_bind_result($statement, $userID, $name, $username, $password, $points);  

        while(mysqli_stmt_fetch($statement)){
            $response["success"] = true;  
            $response["name"] = $name;
            $response["username"] = $username;
        }
    }else{
        $response["success"] = false;
    }

    echo json_encode($response);
?>

1 个答案:

答案 0 :(得分:0)

你可以在没有第一个SELECT命令的情况下在SQL中执行此操作,如:

UPDATE `user` SET `points` = (
    CASE
        WHEN `points` > 12500 THEN `points` = `points` - ?
        ELSE `points`=`points`
    END
) WHERE username = ?