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")
        if not stock:
            return apology("Missing Stock")
        elif not shares:
            return apology("Missing Shares")
        elif stockDict==None:
            return apology("Invalid Symbol")
            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.")
                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)
                    for row in some:
                        if row['stock']==stock:
                            db.execute("UPDATE stocks SET shares=:newShares WHERE id=:address", newShares=oldShares+shares, address=address)
                            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.


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 = ?

  • 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 Jun 29 '20 at 15:40
  • Added further info to the answer. – DinoCoderSaurus Jun 29 '20 at 21:02

You must log in to answer this question.

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