Skip to content

Instantly share code, notes, and snippets.

/buy.php Secret

Created August 29, 2016 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/9cdfb20990cf26b56d80d59e2fc500fc to your computer and use it in GitHub Desktop.
Save anonymous/9cdfb20990cf26b56d80d59e2fc500fc to your computer and use it in GitHub Desktop.
buy.php - shared from CS50 IDE
<?php
// configuration
require("../includes/config.php");
$number = isset($_POST["number"]) ? $_POST["number"] : 0;
$symbol = isset($_POST["symbol"]) ? $_POST["symbol"] : "";
$spent = lookup($symbol)["price"] * $number;
$cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
$_owned = CS50::query("SELECT shares FROM Stocks WHERE user_id = ? AND symbol = ?", $_SESSION["id"], $symbol);
$owned = isset($_owned[0]["shares"]) ? $_owned[0]["shares"] : 0;
$new_cash = $cash[0]["cash"] - $spent;
$new_shares = $owned + $number;
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// else render form
render("/../views/buy_form.php", ["title" => "Bought"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST" && lookup($symbol) != false && $number != false)
{
// check valid number entered
if (preg_match("/^\d+$/", $_POST["number"]) != true)
{
apologize("Please enter a positive integer.");
}
// check user has enough cash
if ($spent > $cash[0]["cash"])
{
apologize("You do not have enough cash.");
}
// edit the database
$temp = CS50::query("INSERT INTO Stocks (user_id, symbol, shares) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = ?", $_SESSION["id"], $symbol, $number, $new_shares);
$_temp = CS50::query("UPDATE users SET cash = ? WHERE id = ?", $new_cash, $_SESSION["id"]);
render("/../views/buy_template.php", ["number" => $number, "symbol" => $symbol, "spent" => $spent]);
}
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
apologize("Invalid entry.");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment