0
<?php
require("../includes/config.php"); 

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    if (empty($_POST["stock"]))
    {
        apologize("You must provide the stock you want to sell.");
    }

    // lookup the stock's name
    $stock = lookup($_POST["stock"]);
    if ($stock === false)
    {
        apologize("Invalid stock!");
    }


    // to make sure the stock is in the user's stocks
    $rows = CS50::query("SELECT symbol FROM stocks WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["stock"]));
    if ($rows["symbol"] === false)
    {
        apologize("You do not have any stocks in that company.");
    }

    // query database to get the number of shares
    $rows = CS50::query("SELECT shares FROM stocks WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["stock"]));
    // if that stock doesn't exist, apologize
    if ($rows === false)
    {
        apologize("You do not have any stocks in that company.");
    }

    // store the amount of shares
    $shares = $rows[0]["shares"];

    // calculate the value of all shares
    $value = $stock["price"] * $shares;

    // delete the stock from the database
    $query = CS50::query("DELETE FROM stocks WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["stock"]));
    if ($query === false)
    {
        apologize("You don't have this stock!");
    }

    // add the stock's price to the user's cash
    $query = CS50::query("UPDATE users SET cash = cash + ? WHERE id = ?", $value, $_SESSION["id"]);
    if ($query === false)
    {
        apologize("An error has occurred.");
    }
    redirect("/");
}
else
{
    render("sell_form.php", ["title" => "Sell Form"]);
}
?>
1
// to make sure the stock is in the user's stocks
$rows = CS50::query("SELECT symbol FROM stocks WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["stock"]));
if ($rows["symbol"] === false)
{
    apologize("You do not have any stocks in that company.");
}

Instead of doing this, why not check to see how many $rows are returned by your CS50::query?

PHP's count() may help.

If it is exactly one row, you can proceed; otherwise, you can apologize() and exit with error.

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .