0

I have buy and sell implemented and I can successfully use them to buy and sell the shares but I can't make sure the user only sells shares that they have.I get the number of shares to sell from the user in the form:

 <div class="form-group">
            <input autocomplete="on" autofocus class="form-control" name="num" placeholder="enter amount" type="text"/>
        </div>

and then I try to compare it to the number of shares in the portfolio but it doesn't seem to work since it will go into the negative

else if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // validate submission

$stock = lookup($_POST["symbol"]);
      $shares = CS50::query("SELECT shares FROM portfolios WHERE user = ? 
AND symbol = ?",     $_SESSION["id"], $_POST["symbol"] );

       if ($shares < $_POST["num"])
       {
           apologize("you don't have that many");
       }
  • Have you verified the number of shares AND symbol AND userid coming from both the form and from the database? My swag is that either the form data isn't correct or it's getting the wrong data from the db. – Cliff B Jul 6 '16 at 19:52
  • I've checked and double-checked I can't find a discrepancy. – Evan Jul 6 '16 at 20:03
  • I believe that you've checked at the source, but have you tried outputting the data from within the php code to the server screen as a printf? It's entirely possible that something is happening downstream. – Cliff B Jul 6 '16 at 20:10
  • Oh right I forgot to do that. Okay I tried to print the value of $shares and it said "array to string conversion" even if I try to print it with a foreach loop. So the problem is the variable is an array for some reason but I don't know why or how to fix it. – Evan Jul 6 '16 at 20:30
0

When you do a query, it returns the result set to the variable as rows. Even if it's just one value in one row, you need to extract the data.

    $rows = query("SELECT symbol, shares FROM portfolio WHERE ID = ?", $_SESSION["id"]);

    foreach ($rows as $row)
    {
        // you'll have to figure it out from here. ;-)
    }

But this gives you the structure.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • thanks I finally thought of a way to get it to work. I put the if condition inside the for each Loop. – Evan Jul 6 '16 at 23:25

You must log in to answer this question.

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