-
-
Save anonymous/e381091fd3ade8268d1073787c368cd3 to your computer and use it in GitHub Desktop.
buy.php - shared from CS50 IDE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require("../includes/config.php"); | |
$method = $_SERVER["REQUEST_METHOD"]; | |
if ($method == "GET") | |
{ | |
render("buy_form.php", ["title" => "Buy"]); | |
} | |
elseif ($method == "POST") | |
{ | |
// make sure fields filled out | |
if (empty($_POST["symbol"]) || empty($_POST["shares"])) | |
{ | |
apologize("Please fill out all fields before continuing"); | |
} | |
// make sure shares are a nonnegative int | |
if (!preg_match("/^\d+$/", $_POST["shares"])) | |
{ | |
apologize("Please enter a nonnegative whole number of shares"); | |
} | |
$stock = lookup($_POST["symbol"]); | |
if ($stock == false) | |
{ | |
apologize("Stock does not exist"); | |
} | |
$cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]); | |
if ($_POST["shares"] * $stock["price"] > $cash[0]["cash"]) | |
{ | |
apologize("You do not have enough money to buy that many stock"); | |
} | |
$buyCheck = CS50::query("INSERT INTO portfolios (user_id, symbol, shares) | |
VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", | |
$_SESSION["id"], strtoupper($_POST["symbol"]), $_POST["shares"]); | |
if ($buyCheck != 1) | |
{ | |
apologize("Error inserting info into portfolios table"); | |
} | |
$cashCheck = CS50::query("UPDATE users SET cash = cash - ? WHERE id = ?", $stock["price"] * $_POST["shares"], $_SESSION["id"]); | |
if ($cashCheck !== 1) | |
{ | |
apologize("Eror updating user cash in users table"); | |
} | |
$_POST["company"] = $stock["name"]; | |
$_POST["price"] = $stock["price"]; | |
render("buy_result.php", ["title" => "Buy"]); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment