0

In the function buy when I am purchasing some stock, every query that i have mentioned on different conditions are getting implemented, I am unable to guess as why It is happening. Here is my code:

def buy():
    """Buy shares of stock"""
    if request.method=="GET":
        return render_template("buy.html")
    else:
        stock=request.form.get("stock").upper()
        shares=float(request.form.get("shares"))
        stockDict=lookup(stock)
        if not stock:
            return apology("Missing Stock")
        elif not shares:
            return apology("Missing Shares")
        elif stockDict==None:
            return apology("Invalid Symbol")
        else:
            price=float(stockDict['price'])
            cashList=db.execute("SELECT cash, username from users WHERE id=?",session["user_id"])
            currentCash= cashList[0]['cash']
            username= cashList[0]['username']
            if currentCash< price*shares:
                return apology("You do not have enough money to buy the shares.")
            else:
                some=db.execute("SELECT id, stock, shares FROM stocks WHERE user=?", username)
                if len(some)==0:
                    db.execute("INSERT INTO stocks(user, stock, shares) VALUES (?,?,?)",username, stock, shares)
                else:
                    for row in some:
                        if row['stock']==stock:
                            address=row['id']
                            oldShares=row['shares']
                            db.execute("UPDATE stocks SET shares=:newShares WHERE id=:address", newShares=oldShares+shares, address=address)
                        else:
                            db.execute("INSERT INTO stocks(user, stock, shares) VALUES (?,?,?)",username, stock, shares)
                return redirect("/")

The actual problem here is with the queries that I have written after the statementif len(some)==0 because even if there are conditional statements, the queries are getting implemented.

1 Answer 1

0

All those queries will run if user holds any stock, whether it is the selected one or not. Don't you only want some to be the rows for this user and this stock? To limit the query so it only selects the desired stock, it would be something like this:

SELECT id, stock, shares FROM stocks WHERE user=? AND stock = ?

2
  • Yeah, i want it, but I want to implement further queries only after some conditions, how do i get it? How do I avoid multiple implementation
    – noob_dev17
    Commented Jun 29, 2020 at 15:40
  • Added further info to the answer. Commented Jun 29, 2020 at 21:02

You must log in to answer this question.

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