I wrote some code for sell.php in CS50 Finance, but the cash field in the users table does not update accurately. The code for updating this field is towards the bottom.
This is really driving me crazy. My code is below. Any help would be greatly appreciated.
Thanks!
<?php
// configuration
require("../includes/config.php");
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//check if portfolio is empty
$portfolio = CS50::query("SELECT * FROM portfolio WHERE user_id = ?", $_SESSION["id"]);
if(empty($portfolio))
{
apologize("No stocks to sell.");
}
//get values to set up sell_form.php
else
{
$rows = CS50::query("SELECT symbol, shares FROM portfolio WHERE user_id = ?", $_SESSION["id"]);
$cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
$balance = number_format($cash[0]["cash"], 2);
$positions = [];
foreach($rows as $row)
{
$company = lookup($row["symbol"]);
if($company != false)
{
$total = number_format($company["price"] * $row["shares"], 2);
$positions[] = [
"name" => $company["name"],
"symbol" => $company["symbol"],
"price" => $company["price"],
"shares" => $row["shares"],
"total" => $total
];
}
}
// render sell_form
render("sell_form.php", ["positions" => $positions, "balance" => $balance, "title" => "Sell"]);
}
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$symbol = strtoupper($_POST["symbol"]);
$shares = $_POST["shares"];
//check the stock symbol
$valid = lookup($symbol);
if($valid == false)
{
apologize("Invalid stock symbol");
}
$stocks = CS50::query("SELECT * FROM portfolio WHERE user_id = ? AND symbol = ?", $_SESSION["id"], $symbol);
$money = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
if(empty($stocks))
{
apologize("You have no shares of {$stock["name"]} ($symbol) stock.");
}
if($_POST["shares"] > $stocks[0]["shares"])
{
apologize("You do not own $shares shares of {$stock["name"]} ($symbol) stock.");
}
//calculate new balance
$sale = lookup($symbol);
$transaction = $sale["price"] * $shares;
$funds = $money[0]["cash"];
$formatted_balance = number_format($transaction + $funds, 2);
//update tables
CS50::query("UPDATE users SET cash = ? WHERE id = ?", $formatted_balance, $_SESSION["id"]);
CS50::query("UPDATE portfolio SET shares = shares - ? WHERE user_id = ? AND symbol = ?", $shares, $_SESSION["id"], $symbol);
if($shares == $stocks[0]["shares"])
{
CS50::query("DELETE FROM portfolio WHERE user_id = ? AND symbol = ?", $_SESSION["id"], $symbol);
}
redirect("/index.php");
}
?>