-1

I have The following code

 $stake =  mysqli_real_escape_string($link,$_POST['stake'][0]);
 $payout =   mysqli_real_escape_string($link,$_POST['payout'][0]);
 $todds = mysqli_real_escape_string($link,$_POST['todds'][0]);
 $accabal =  mysqli_real_escape_string($link,$_POST['balance'][0]);
 $invoiceid =  $_POST['invoiceid'];


//run sql query for every iteration

$charge = mysqli_query($dba, "UPDATE users SET balance = $accabal- $stake WHERE username='".$_SESSION['username']."'") ;

$_SESSION["balance"] =  $accabal- $stake ;


        $insert = mysqli_query($link,"INSERT INTO `receipts`(`Match`, `Selection`, `Odd`,`Account`,`Stake Amount`,`Payout`,`Total Odds`,`invoiceid`,`Kickoff`) VALUES ('$match','$selection','$odd','$account','$stake','$payout','$todds','$invoiceid','$kickoff')");
    
        
        if(!$insert)
        {
            $error = true;
            $error_msg = $error_msg.mysqli_error($link);            
        }
  
      }  
  
    //check your error status variable and show your output msg accordingly.
    @session_start();

    if(true){
      $_SESSION['rec'] = $_POST['invoiceid'];
       $_SESSION['success'] = 1;
       header("Location: welcome.php");
    }

?>

I need the code to check weather the balance is insufficient to make the bet ($balance-$stake < 0) and stop the code if the balance is set to be negative before placing the bet, How do I edit My code to do this?

  • 2
    Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating user provided values into the query. – Barmar Jul 28 '22 at 21:42
  • Sure, will try to research and edit my code thanks once again – Woza Station Namibia Jul 28 '22 at 22:30
  • Why are you subtracting `$stake` from `$accabal` instead of from `balance`? – Barmar Jul 28 '22 at 22:36

1 Answers1

1

Use a SELECT query to get the current balance, and check if it's more than the stake.

$stmt = $link->prepare("SELECT balance FROM users WHERE username = ?");
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($balance >= $stake) {
    // code that updates the tables
} else {
    // report not enough balance
}
Barmar
  • 741,623
  • 53
  • 500
  • 612