0

The purpose of this script is to allow the user to add "money" to their account and then withdraw the money. This whole task is a fictitious one for school so i'm not worried about security or using real money or anything like that.

so far the user has the ability to add money. But I cannot get the withdraw to work.

    $funds = $_POST['funds'];
    $withdraw_or_add = $_POST['list'];


if($withdraw_or_add == "add"){
    $sql = "UPDATE users ". "SET userFunds = $funds ". "WHERE userId = 1";
} else {
    $info = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE userId = '1'"));
    $new_fund == $info['userFunds'] - $funds;
    $sql = "UPDATE users ". "SET userFunds = $new_fund ". "WHERE userId = 1";
}

This is the code I have written for this section. When i used it on the server i get this message in return.

Could not update data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE userId = 1' at line 1

My knowledge of PHP is not fantastic. So any help would be much appreciated.

Craig Harkins
  • 153
  • 2
  • 10
  • 1
    `users ` in your query is any constant or table name itself? – Milan Gupta Nov 15 '16 at 11:16
  • @MilanGupta It's the name of the table. – Craig Harkins Nov 15 '16 at 11:17
  • 1
    Try writing query like this: `"UPDATE users SET userFunds = ' ".$funds." ' WHERE userId = 1";` – Milan Gupta Nov 15 '16 at 11:18
  • 1
    @MilanGupta Okay i did that and now when i withdraw "money" it takes the number that should be used for subtraction and just uses that as the new figure. So when i want to take away 5 from 20 it should be 15. But instead it just changes to 5. – Craig Harkins Nov 15 '16 at 11:22
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Nov 16 '16 at 11:07

1 Answers1

1

Try this:

$funds = $_POST['funds'];
$withdraw_or_add = $_POST['list'];


if($withdraw_or_add == "add")  
{
  $sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1";  
  $sql =  mysql_query($sql) or die(mysql_error());
}   
else  
{
  $info = mysql_query("SELECT * FROM users WHERE userId = '1'");
  $info = mysql_fetch_assoc($info);
  $new_fund = $info['userFunds'] - $funds;
  $sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1";  
  $sql =  mysql_query($sql) or die(mysql_error());
}
Milan Gupta
  • 1,181
  • 8
  • 21