使用Mysql进行字段减法

时间:2016-07-14 22:37:13

标签: php mysql

请有人帮我解决这个新手问题,我一直在努力解决这个问题:

下面我的代码的第一部分是验证检查,团队有足够的资金购买玩家;第二部分将玩家添加到团队表中;但是我还需要更新Teams表以从Available_Funds等待成功验证中删除玩家的成本。

我的问题是双重的...验证查询不能正常工作。我想我需要在$ result< 0 check附近添加一个mysqli函数,但我不确定是哪一个。我还需要相应地更新Teams表中的Avaliable_Funds;但我不确定将它与Insert Into语句结合起来的必要语法。将非常感激地收到关于这两个相关问题的任何指导。

这是我的代码中的相关部分。 $ Cost是正确发布的变量。 (我已经注释掉了目前没有工作的部分):

//$result = $mysqli->query("Select (Available_Funds-'{$Cost}') as check From Teams Where Team_ID = '{$Team}'");
    //if  ($result<0) {$error.='<p>You have insufficient funds</p>';}


else
    $sql="Insert Into Players (Player_Name,Status,Type_ID,Team_ID) Values ('" . $player_name . "','Active','" . $Type . "','" . $Team . "')";
    $result = $mysqli->query($sql); }

//$sql="Update Teams set Available_Funds=(Available_Funds-'{$Cost}')";
$result = $mysqli->query($sql);

非常感谢您对此提供任何帮助!

1 个答案:

答案 0 :(得分:0)

更改您的第一个查询。如果团队有足够的资金,下面的查询将返回匹配

$sql =  "SELECT * FROM ( "
        ."SELECT Available_Funds - $Cost as balance " 
        ."FROM Teams Where Team_ID = '$Team' "
        .") AS t "
        ."WHERE t.balance >= 0"

$result = $mysqli->query($sql);

内部查询返回剩余余额。然后外部查询选择该结果,如果该余额为非负数。

处理结果:

if($result===false){//DB error. Probably bad query. See $mysqli->error        
    $error = "Server error: no changes were made";
}elseif($result->num_rows===0){//unknown $Team or insufficient funds        
    $error = "Insufficient funds";
}else{
    //team has sufficient funds. The next two queries should be run
    //as a transaction, meaning if either one fails, all changes
    //should be rolled back. This is to avoid a team getting a player
    //without paying, or a team paying, but not getting the player

    //server won't commit changes until we say so
    $mysqli->autocommit(false);

    //learn to use prepared statements. This is dangerous
    $sql2 =   "Insert INTO Players (Player_Name,Status,Type_ID,Team_ID) "
             ."VALUES ('$player_name','Active','$Type','$Team')";

    $sql3 =   "Update Teams SET Available_Funds=(Available_Funds-$Cost) "
             ."WHERE Team_ID = '$Team'";        

    if($mysqli->query($sql2) && $mysqli->query($sql3)){
        $mysqli->commit(); //save changes
    }else{
        $mysqli->rollback(); //undo changes
        $error = "Server error: no changes were made";
    }
    $mysqli->autocommit(true); //end transaction mode
    $mysqli->close(); //close connection
}

我应该重新迭代:在查询中直接插入用户定义的值是非常糟糕的安全做法。学习使用预备语句。祝你好运: - )