I just finished sell.php, but I had to use $cash[0]["cash"], to get cash out of my query. This dos not feel right. The code works, but I feel it is wrong. Is there a better way to do this??


    // configuration

    // if user reached page via GET (as by clicking a link or via redirect)
    if ($_SERVER["REQUEST_METHOD"] == "GET")
        // get symbols of stocks user owns
        $symbols = CS50::query("SELECT symbol FROM portfolios WHERE user_id = ?", $_SESSION["id"]);
        // render form
        render("sell_form.php", ["title" => "Sell", "symbols" => $symbols]);

    // else if user reached page via POST (as by submitting a form via POST)
    else if ($_SERVER["REQUEST_METHOD"] == "POST")
        // if user did not select a symbol
        if (empty($_POST["symbol"]))
            apologize("You must select a stock to sell.");
        // lookup symbol
        $stock = lookup($_POST["symbol"]);
        // lookup users cash
        $cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
        // get number of shares of symbol that the user owns
        $shares = CS50::query("SELECT shares FROM portfolios WHERE symbol = ?", $stock["symbol"]);
        // validate submission
        if (empty($shares))
            apologize("You don't have any of that stock to sell");
        // remove stocks from portfolio and update cash
        $new_cash = $cash[0]["cash"] + ($stock["price"] * $shares[0]["shares"]);
        CS50::query("DELETE FROM portfolios WHERE user_id = ? AND symbol = ?", $_SESSION["id"] , $stock["symbol"]);
        CS50::query("UPDATE users SET cash = ? WHERE id = ?", $new_cash, $_SESSION["id"]);
        // back to portfolio        

It is right. CS50::query() always returns an array of rows, even when the result is just one row.

That's why you should use the [0], as you have correctly done.

You can ctrl+F this:

// first (and only) row
$row = $rows[0];

inside the login.php file, which was written by the staff, and you'll see that they, too, had to use $rows[0] to extract a $row.

If you want to feel better about yourself, you could do this to make it prettier:

$rows = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
$cash = $rows[0]["cash"];
  • Everything else in php is so pretty, this was ugly, it didn't seem right. Especially with a language so loosely typed. Thanks for the help. Nov 20 '16 at 2:38
  • If this answers your question, please click the green check mark so we can close this! Nov 20 '16 at 2:40

You must log in to answer this question.

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