Whenever I try to run sell.php, the code will neither add to the balance nor add the transaction to the history table. There's nothing in the code that seems to be the cause of it. Why is this happening? I formatted the tables correctly.




    //If user arrived via "GET"
    if ($_SERVER["REQUEST_METHOD"] == "GET")
        //render form
        render("sell_form.php", ["title" => "Sell"]);

    //else if user arrived via "POST"
    else if ($_SERVER["REQUEST_METHOD"] == "POST")
        //Gather info
        $info = query("SELECT shares FROM `stocks` WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["symbol"]));
        $price = lookup(strtoupper($_POST["symbol"]));
        $addcash = $price["price"] * floatval($info["shares"]);

        //If user owns no shares of this stock
        if ($info == [])
            apologize("You don't own any shares of this stock.");

        //Else, sell shares
            query("DELETE FROM `stocks` WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["symbol"]));
            query("UPDATE users SET cash = cash + ? WHERE id = ?", $addcash, $_SESSION["id"]);
            query("INSERT INTO `history` (id, action, symbol, shares, price, date) VALUES(?, \"Sell\", ?, ?, ?, CURRENT_TIMESTAMP)", $_SESSION["id"], strtoupper($_POST["symbol"]), $_POST["shares"], $price["price"]);

            //Redirect back


A query() with SELECT will return an array, even if this array contains only one row. So instead of

$addcash = $price["price"] * floatval($info["shares"]);

you should have:

$addcash = $price["price"] * floatval($info[0]["shares"]);

Let me know if that fixes it.

If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

  • O hai +1 I'm just checking in on Stack
    – i_am_david
    Oct 8 '15 at 0:47

You must log in to answer this question.

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