0

Sell.php

     // if user reached page via GET (as by clicking a link or via redirect)
    if ($_SERVER["REQUEST_METHOD"] == "GET")
    {
        // else render form
        $rows = CS50::query("SELECT * FROM Portfolio WHERE  id = ?", $_SESSION["id"]);
        render("sell_form.php", ["title" => "Sell","rows"=> $rows]);
    }
    //else if user reached page via a post
     else if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        //Check for the stocks
        $stock = lookup($_POST["symbol"]);

        if($stock == false)
            apologize("Stock symbols are invalid");

        //Display the stocks owned by the user
        $rows = CS50::query("SELECT * FROM Portfolio WHERE  id = ?", $_SESSION["id"]);

        //Store no. of shares in a variable
        $shares = 0;

       if(count($rows == 1))
         $shares = $rows[0]["shares"];

        //Store cash withdrawn in a variable which computes cash by multiplying no of shares and price of each stock
        $cash = $_POST["shares"] * $stock["price"];

        //Delete stocks from Portfolio
        $sold = CS50::query("DELETE FROM Portfolio WHERE user_id = ? AND symbol = ?",$_SESSION["id"],$_POST["symbol"]);

       if($sold == false)
         apologize("Couldn't sell stocks");

       //Update the cash in the balance
       $balance = CS50::query("UPDATE users SET cash = cash + ? WHERE id = ?",$cash,$_SESSION["id"]);

       if($balance == false)
         apologize("Failed to update the balance");

       redirect("/");
    }
?>

Sell_form.php

<form action="sell.php" method="post">
    <fieldset>
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Symbol" type="text"/>
        </div>
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="shares" placeholder="no_of_shares" type="text"/>
        </div>
          <?php foreach ($rows as $row): ?>

            <?= $row["symbol"] ?>
            <?= $row["shares"] ?>

        <?php endforeach ?>
        <div class="form-group">
            <button class="btn btn-default" type="submit">
                <span aria-hidden="true" class="glyphicon glyphicon-log-in"></span>
                Sell
            </button>
        </div>
    </fieldset>
</form> 

I am getting this error.

undefined index

I have read an earlier answer but I don't seem to understand it.

1

You are using the wrong return value. From the pset specs:

If query is instead passed a DELETE, INSERT, or UPDATE statement, it will return a non-negative integer that represents the number of rows deleted, inserted, or updated, respectively.

1

You must log in to answer this question.

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