Function problem

Drew Fisher drew at level3.net
Fri Mar 29 10:35:39 EST 2002


> 
> G'day:
> 
> 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 not entirely sure, but I'll show you what I would do.

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

Yes.

> 
> ----------
> 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()
> 

Instead of using fetchone, try using fetchall:
query = c.execute ("SELECT category FROM categories")
list = c.fetchall ()
for entry in list:
	print "<option value='%s'>%s</option>" % (entry, entry)
print "</select>"
.
.


This just does the one query and pulls out all of the data at one time. 
The c.fetchone() hits the database each time the while loop repeats.

Hope this help.

Drew Fisher




More information about the Python-list mailing list