(Login: demo, 123)
In the above example, I demonstrate what a drop down list on a Python webpage looks like.
Here’s the code:
#!/usr/bin/python print "Content-type: text/html\n\n" print "" print "" print "" #start here: init(1) print "" print ""Select Quiz Dropdown Example " print "" print "" print "" print "" print "" #GLOBAL VARIABLES USERNAME = 'admin' PASSWORD = 'pwd' DB = 'online-quiz' import MySQLdb def init(userid): #DEBUG: #print("show form" + str(userid) + "
") print "
>>Click here to see it in action<<
(The MySQL database calls are outlined with the red borders)
Basically, inside my “td” (tabledef) tag I am making a database connection and executing a sql string to return the contents of the drop down list
I am doing this before the “select” tag begins, and then in the “select” tag I am using the Python for loop.
(I am using the str() Python function to convert the numeric value to a string. Sometimes I don’t need to do this, but if Python “complains”, here it the “tool” to fix it).
Python MySQL Cursor
Fairly simple stuff. I am using a “python cursor object” to hold to result of the “sql2” database query, and then looping the cursor’s contents which has 2 columns, Zero based index of 0 and 1.
–> So I can assign row[0] to the variable qui_id:
cursor = conn.cursor() cursor.execute(sql) print "<select name='qui_id' id='qui_id' class='ddquiz'>" print "<option value=''><i>(Select Quiz)</i></option>" for row in cursor: qui_id = row[0] qui_quiz = row[1] #print "<option value=>" + qui_quiz print "<option value=" + str(qui_id) + ">" + str(qui_quiz) + "</option>"
Python for loop with index
The index for my Python for loop is the id for the selected quiz, so each item in the select drop down box is unique.
I assign the unique id to the value attribute of the “select” tag.
print "<option value=" + str(qui_id) + ">" + str(qui_quiz) + "</option>"
***…so the qui_id of the quiz is the value and then what shows in the dropdown (select) box is the actual text value (qui_quiz).
print "<td>" conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB) sql="SELECT qui_id,qui_quiz FROM tblQuizzes WHERE qui_user_id = " + userid #DEBUG: #print("<br>" + str(sql) + "<br>") cursor = conn.cursor() cursor.execute(sql) print "<select name='qui_id' id='qui_id' class='ddquiz'>" print "<option value=''><i>(Select Quiz)</i></option>" for row in cursor: qui_id = row[0] qui_quiz = row[1] #print "<option value=>" + qui_quiz print "<option value=" + str(qui_id) + ">" + str(qui_quiz) + "</option>" print "</select>" print "</td>"
>>Click here to see it in action<<
Questions?