RedditPP Mascot

RedditPP

r/cs50 • … • u/Arponare

buy.php adding new entry into database when purchasing more shares of stocks user already owns

So the title is pretty much self explanatory. I followed Zamyla's example and I plugged in the appropiate values. I even made sure to uppercase symbol using strtoupper and I made sure the function was actually doing so doing so by using dump. Nevertheless if I purchase 4 stocks of Sprint (S) it subtracts my money just fine and redirect me to index. The trouble occurs if I then decide to buy more shares of sprint. For some reason, instead of simply changing from 4 to 6 shares in my database, it displays both the 4 shares that I bought earlier, plus the 2 shares I just purchased.

Here is the code fragment that handles that

//if symbol entered is valid

//make sure symbol string is uppercase $symbol = strtoupper($_POST["symbol"]);

CS50::query("INSERT INTO user_stocks (users_id, symbol, shares) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $_SESSION["id"], $symbol, $_POST["shares"]);

It also has to be said that when selling a stock. It does list both of them but selling one results in selling both, so it's even more baffling as to why the code fragment above doesn't update it as opposed to create a new one like it does. Any help would be greatly appreciated.

— 0