Function problem

Emile van Sebille emile at fenx.com
Fri Mar 29 10:31:28 EST 2002


Michael Hall
> Can someone tell me why this function stops printing after looping
through
> the <option> section, before </select> ? Everything prints to the
browser
> up to the last while loop, then from </select> there is nothing more.
>
> I'm new to Python and tend to try to use PHP idioms too much, but I
can't
> see what is wrong here.
>
> Also, am I using MySQLdb's c.close() correctly here? Any really bad
Python
> in this example?
>
> ----------
> def ShowCats():
> print "<form
action=\"http://olc.localdomain/cgi-bin/shopcat/shopcat.py\"
method=\"post\">"
> print "<select name=\"cat\">"
> db = MySQLdb.connect(user="abc",passwd="xyz",db="shopcat_db")
> c = db.cursor()
> query = c.execute("SELECT category FROM categories")
> while query:
> result = c.fetchone()
> category = result[0]
> print "<option value='%s'>%s</option>" % (category,category)
> print "</select>"
> print "<input type='hidden' name='action' value='showall'>"
> print "<input type='submit' value='SUBMIT'>"
> print "</form>"
> c.close()
>

[I suspect you're using tabs for indentation.  Some newsreaders (mine
included) lose tabbed indentation.  If you post with spaces, readers are
more likely to respond as they won't need to 'clean up the code' first.]

It doesn't look like the while loop terminates.  Try something like:

query = c.execute("SELECT category FROM categories")
result = c.fetchone()
while result:
    category = result[0]
    print "<option value='%s'>%s</option>" % (category,category)
    result = c.fetchone()


And there's no 'really bad' code in there.  I tend to keep SQL
connection and authentication related information in a separate local
module and then:

from sqldata import cache
catdata = cache("SELECT category FROM categories")
for cat in catdata:
    print "<option value='%s'>%s</option>" % (cat.category,cat.category)

but that's really just personal choice.

HTH,

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list