Now it’s time to add some functionality to add quizzes.
So first we have to make a MySQL table to hold the main quiz text:
(view structure after the table is created)

Now this is where the questions for the quiz will be entered. Please note, that this is a “parent/child” type database setup, the main quiz will be selected and then the questions for that quiz can be added.
(this is the view before the table is actually created)

(I’ll probably be adding more fields to this table as needed)

>>>Click to see it in action together<<<
Breakdown:
Login With: (We created this login form on another post -> Click here)
User Name = ‘demo’
Password = ‘123’
If your login is successful your login user id will be passed to future pages:

…otherwise if you login incorrectly, you’ll get:
**************Login Failed**************
Try Again
Choose What To Do Next (dashboard-quizzes.py)

Here’s the code:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Enter Quizes</title>"
print "</head>"
print "<body>"
#GLOBAL VARIABLES
USERNAME = 'admin'
PASSWORD = 'db-pwd'
DB = 'online-quiz'
import MySQLdb
import os
#import requests #this script doesn't like this (doesn't fail, just blank screen)
# Import modules for CGI handling
import cgi, cgitb
def init():
#read the query params
params = os.environ.get('QUERY_STRING','nichts')
#DEBUG:
#print 'params= ' + str(params)
#print '<br>'
#print '<br>'
res = params.split('=') #TESTS THAT THERE IS A QUERY STRING
#display based on if params were sent
if str(res) == "['']":
#DEBUG:
print ('You should not be here')
print '<br>'
print "<a href='index.py'>You need to login first.</a>"
else:
#DEBUG:
#print ('some params were passed - show them')
print "<h2>What Would You Like To Do?</h2>"
#----------------------------
searchParams = [i.split('=') for i in params.split('&')] #parse query string
for key, value in searchParams:
#print('<b>' + key + '</b>: ' + value + '<br>\n')
if key == 'id':
#print ("Add Quizzes")
print ("<a href='enter-quizzes.py?id=" + str(value) + "'>Add Quizzes</a>")
print '<br>'
#print ("Add Questions for selected quiz")
print ("<a href='select-quiz.py?id=" + str(value) + "'>Add Questions For Selected Quiz</a>")
#----------------------------
#start here:
init()
print "</body>"
print "</html>"
Add Quizzes (enter-quizzes.py)

Here you can add, edit, and delete quizzes.
Here’s the code:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Enter Quizes</title>"
print "</head>"
print "<body>"
#GLOBAL VARIABLES
USERNAME = 'admin'
PASSWORD = 'db-pwd'
DB = 'online-quiz'
import MySQLdb
import os
#import requests #this script doesn't like this (doesn't fail, just blank screen)
# Import modules for CGI handling
import cgi, cgitb
def init():
#read the query params
params = os.environ.get('QUERY_STRING')
#DEBUG:
#print 'params= ' + str(params)
#print '<br>'
#print '<br>'
res = params.split('=') #TESTS THAT THERE IS A QUERY STRING
#display based on if params were sent
if str(res) == "['']":
#DEBUG:
print ('You should not be here')
print '<br>'
print "<a href='index.py'>You need to login first.</a>"
else:
#DEBUG:
#print ('some params were passed - show them')
#get the field values
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('quiz'):
quiz = form.getvalue('quiz')
else:
quiz = "Not set"
if form.getvalue('userid'):
userid = form.getvalue('userid')
else:
userid = "Not set"
#----------------------------
searchParams = [i.split('=') for i in params.split('&')] #parse query string
for key, value in searchParams:
#DEBUG:
#print('<b>' + key + '</b>: ' + value + '<br>\n')
#show the quizzes for user and allow for data entry
if key == 'id':
#when the form initializes, it should be blank
print("<h2>Enter And List Quizzes</h2>")
quiz = "Not set"
userid = value
show_form(value)
#********************
#insert the contents of the form into the table
#********************
show_table(userid)
elif key == 'insert':
print("<h2>Insert Record</h2>")
insert_values(userid,quiz)
show_table(userid)
elif key == 'edit':
print("<h2>Edit Record</h2>")
#uses cgi to parse the querystring, and ability to access individual arguments
userid = cgi.parse_qs( params )["user"][0]
qid = cgi.parse_qs( params )["edit"][0]
#-------------------------
#show the clicked record.
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql = "SELECT qui_quiz FROM tblQuizzes WHERE qui_id=" + qid
cursor.execute(sql)
conn.commit()
for row in cursor:
qui_quiz = row[0]
# Close the connection
conn.close()
#-------------------------
#show the edit version of the form
show_form_edit(userid,qid,qui_quiz)
show_table(userid)
elif key == 'edit2':
userid = form.getvalue('userid')
qid = form.getvalue('qid')
qui_quiz = form.getvalue('qui_quiz')
update_values(qid,qui_quiz,userid)
show_table(userid)
elif key == 'delete':
print("<h2>Delete Record</h2>")
#uses cgi to parse the querystring, and ability to access individual arguments
userid = cgi.parse_qs( params )["user"][0]
delete_values(value,userid)
show_table(userid)
#----------------------------
def insert_values(userid,quiz):
#DEBUG
#print ("<br><br>insert_values<br><br>")
#print ("userid="+ str(userid) + "<br>")
#print ("quiz="+ str(quiz) + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
#Python will handle the escape string for apostrophes and other invalid SQL characters for you
# %d or %i should be used for integer or decimal values.
# %s is used for string values
sql = "INSERT INTO tblQuizzes (qui_user_id,qui_quiz) VALUES (%s, %s)"
args=(userid, quiz)
try:
cursor.execute(sql, args)
#add this to make sure you data is being inserted
conn.commit()
print "<br><font color=green>****************RECORD INSERTED****************</font><br>"
print ("<h3><a href='enter-quizzes.py?id=" + str(userid) + "'>Back</a></h3>")
except error as e:
print("error")
print(e)
return None
# Close the connection
conn.close()
def update_values(quiz_id,quiz,userid):
#DEBUG
#print("edit = " + str(quiz) + " - for QUIZ=" + str(quiz_id) + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
#Python will handle the escape string for apostrophes and other invalid SQL characters for you
sql = "UPDATE tblQuizzes SET qui_quiz = %s WHERE qui_id =%s"
cursor.execute(sql, (quiz,quiz_id))
conn.commit()
print '<br><font color=green>**************Record Updated**************<br>'
print ("<h3><a href='enter-quizzes.py?id=" + str(userid) + "'>Back</a></h3>")
# Close the connection
conn.close()
def delete_values(arg,userid):
#DEBUG
#print("delete = " + arg + " - for user=" + userid + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql="DELETE FROM tblQuizzes WHERE qui_id=" + arg
try:
cursor.execute(sql)
conn.commit()
print "<br><font color=red>****************RECORD DELETED****************</font><br>"
print ("<h3><a href='enter-quizzes.py?id=" + str(userid) + "'>Back</a></h3>")
except error as e:
print(e)
return None
print "<br><font color=red>****************DELETION FAILED!****************</font><br>"
# Close the connection
conn.close()
def show_table(userid):
#DEBUG:
#print("show table<br>")
conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql="SELECT * FROM tblQuizzes WHERE qui_user_id = " + userid
#DEBUG:
#print("<br>" + str(sql) + "<br>")
cursor.execute(sql)
# Get the number of rows in the result set
numrows = cursor.rowcount
print "<table width='100%' border='1px'>"
print "<th>Edit</th><th>Delete</th><th>Quiz</th>"
# Get and display all the rows
for row in cursor:
qid = row[0]
quiz = row[1]
print '<tr>'
print '<td width=2%>'
print "<a href='enter-quizzes.py?edit=" + str(qid) + "&user="+str(userid)+"'>Edit</a>" #need to convert the index to a string
print '</td>'
print '<td width=2%>'
print "<a href='enter-quizzes.py?delete=" + str(qid) + "&user="+str(userid)+"'>Delete</a>" #need to convert the index to a string
print '</td>'
print '<td>' + row[2] + '</td>'
print '</tr>'
print '</table>';
# Close the connection
conn.close()
def show_form(userid):
#DEBUG:
#print("show form<br>")
print "<form action = 'enter-quizzes.py?insert=1' method = 'post'>"
print "<table width='100%' border='0px' bgcolor=lightgreen>"
print "<tr>"
print "<td><strong>User:</strong></td>"
print "<td><input type = 'text' style='background-color:grey' readonly name = 'userid' value='" + str(userid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Quiz:</strong></td>"
print "<td><input type = 'text' name = 'quiz' value=''></td>"
print "</tr>"
print "<tr>"
print "<td><input type = 'submit' value = 'Submit' /></td>"
print "</tr>"
print "</table>"
print "</form>"
def show_form_edit(userid,qid,qui_quiz):
#DEBUG:
#print("show form<br>")
print "<form action = 'enter-quizzes.py?edit2=1' method = 'post'>"
print "<table width='100%' border='0px' bgcolor=lightgreen>"
print "<tr>"
print "<td><strong>User:</strong></td>"
print "<td><input type = 'text' readonly style='background-color:grey' name = 'userid' value='" + str(userid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Quiz ID:</strong></td>"
print "<td><input type = 'text' readonly style='background-color:grey' name = 'qid' value='" + str(qid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Quiz:</strong></td>"
print "<td><input type = 'text' name = 'qui_quiz' value='" + str(qui_quiz) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><input type = 'submit' value = 'Submit' /></td>"
print "</tr>"
print "</table>"
print "</form>"
#start here:
init()
print "</body>"
print "</html>"
Add Questions For Selected Quiz

Click here for more detail on the dropdown select box construction:
This is interesting. When you click the drop down arrow, you’ll see a drop down list of the quizzes currently in your tblQuizzes MySQL table.
JQUERY time:
When you make a selection from the list, the contents of the “div” tag will change to show you how many questions there are for that quiz.
The python script “questions-for-quiz.py” gets called and displays it’s result in the “div” tag
Here is the code for questions-for-quiz.py:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
#note: this (questions-for-quiz.py) needs to be a stand alone html page or the connection to MySQL will not work
#(used to be questions-table.py)
#GLOBAL VARIABLES
USERNAME = 'admin'
PASSWORD = 'db-pwd'
DB = 'online-quiz'
import MySQLdb
import os
def show_results():
#DEBUG:
#print("show table<br>")
#read the query params
params2 = os.environ.get('QUERY_STRING')
#DEBUG:
#print('<b>params2= ' + str(params2) + '</b><br>')
searchParams2 = [i2.split('=') for i2 in params2.split('&')] #parse query string
for key2, val2 in searchParams2:
#DEBUG:
print('<b>' + str(key2) + '</b>: ' + str(val2) + '<br>\n')
if key2 == 'id':
conn2 = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)
cursor2 = conn2.cursor()
sql2= "SELECT `qui_user_id`,`qud_id`, `qud_main_id`, `qud_question`, `qud_correct_answer` FROM `tblQuizzesDetail` INNER JOIN tblQuizzes ON `qud_main_id` = qui_id WHERE qud_main_id = " + str(val2) + " ORDER BY qud_id"
#DEBUG:
#print("<br>sql2= " + str(sql2) + "<br>")
cursor2.execute(sql2)
conn2.commit()
# Get the number of rows in the result set
numrows2 =0
numrows2 = cursor2.rowcount
print("<br><u>" + str(numrows2) + "</u> questions found for selected quiz id: <u>" + str(val2) + "</u>. <a href='quiz-questions-admin.py?id=" + str(val2) + "'>Click to edit</a><br>")
# Close the connection
conn2.close()
#start here:
show_results()
print "</body>"
print "</html>"
Here is the code for select-quiz.py:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Select Quiz To Add Questions</title>"
#note: was add-questions.py
print "<meta http-equiv='Cache-Control' content='no-cache, no-store, must-revalidate' />"
print "<meta http-equiv='Pragma' content='no-cache' />"
print "<meta http-equiv='Expires' content='0' />"
#---------------------------------------------------------------------
#jquery
print "<script src='https://code.jquery.com/jquery-3.5.0.js'></script>"
print "<script>"
print "jQuery(document).ready(function($) {"
print " $('#qui_id').change(function($){"
print " var q3= jQuery(this).val();"
print " var page= 'questions-for-quiz.py';"
print " var page2= page + '?id=' + q3 ;"
print " jQuery('#DisplayDiv').load(page2);"
print " });"
print "});"
print "</script>"
#---------------------------------------------------------------------
print "</head>"
print "<body>"
#GLOBAL VARIABLES
USERNAME = 'admin'
PASSWORD = ''
DB = 'online-quiz'
import MySQLdb
import os
#import requests #this script doesn't like this (doesn't fail, just blank screen)
# Import modules for CGI handling
import cgi, cgitb
def init():
#read the query params
params = os.environ.get('QUERY_STRING')
#DEBUG:
#print 'params= ' + str(params)
#print '<br>'
#print '<br>'
res = params.split('=') #TESTS THAT THERE IS A QUERY STRING
#display based on if params were sent
if str(res) == "['']":
#DEBUG:
print ('You should not be here')
print '<br>'
print "<a href='index.py'>You need to login first.</a>"
else:
#DEBUG:
#print ('some params were passed - show them')
#get the field values
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('userid'):
userid = form.getvalue('userid')
else:
userid = "Not set"
if form.getvalue('qui_id'):
qui_id = form.getvalue('qui_id')
else:
qui_id = "Not set"
#----------------------------
searchParams = [i.split('=') for i in params.split('&')] #parse query string
for key, value in searchParams:
#DEBUG:
#print('<b>' + key + '</b>: ' + value + '<br>\n')
#show the quizzes for user and allow for data entry
if key == 'id':
#when the form initializes, it should be blank
print("<h2>Select Quiz And Enter Questions And Answers</h2>")
userid = value
show_form(value)
#********************
#insert the contents of the form into the table
#********************
#show_table(userid)
#print "<font size=1>start tablediv</font><br>"
print "<table>"
print "<tr>"
print " <td align= left>"
print " <div id='DisplayDiv' style='background-color:white;'>"
print " <!-- This is where questions-for-quiz.py should be inserted -->"
print " </div>"
print " </td>"
print "</tr>"
print "</table>"
#print "<font size=1>end tablediv</font><br>"
#----------------------------
def show_table(userid):
#DEBUG:
#print("show table<br>")
conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)
cursor = conn.cursor()
#sql="SELECT * FROM tblQuizzesDetail WHERE qui_user_id = " + userid
sql= "SELECT `qui_user_id`,`qud_id`, `qud_main_id`, `qud_question`, `qud_correct_answer` FROM `tblQuizzesDetail` INNER JOIN tblQuizzes ON `qud_main_id` = qui_id WHERE qui_user_id = " + userid + " ORDER BY qud_main_id "
#DEBUG:
#print("<br>" + str(sql) + "<br>")
cursor.execute(sql)
# Get the number of rows in the result set
numrows = cursor.rowcount
print "<table width='100%' border='1px'>"
print "<th>Edit</th><th>Delete</th><th>Question</th><th>Answer</th>"
# Get and display all the rows
for row in cursor:
qid = row[0]
quiz = row[1]
print '<tr>'
print '<td width=2%>'
print "<a href='enter-quizzes.py?edit=" + str(qid) + "&user="+str(userid)+"'>Edit</a>" #need to convert the index to a string
print '</td>'
print '<td width=2%>'
print "<a href='enter-quizzes.py?delete=" + str(qid) + "&user="+str(userid)+"'>Delete</a>" #need to convert the index to a string
print '</td>'
print '<td>' + str(row[3]) + '</td>'
print '<td>' + str(row[4]) + '</td>'
print '</tr>'
print '</table>';
# Close the connection
conn.close()
def show_form(userid):
#DEBUG:
#print("show form<br>")
#print "<html>"
#print "<head>"
#print "</head>"
#print "<body>"
print "<form action = 'add-questions.py?insert=1' method = 'post'>"
print "<table width='500px' border='0px' bgcolor=lightgreen>"
print "<tr>"
print "<td><strong>User:</strong></td>"
print "<td><input type = 'text' style='background-color:grey' readonly name = 'userid' value='" + str(userid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Select Quiz From List:</strong></td>"
print "<td>"
conn2 = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)
sql2="SELECT qui_id,qui_quiz FROM tblQuizzes WHERE qui_user_id = " + userid
#DEBUG:
#print("<br>" + str(sql) + "<br>")
cursor2 = conn2.cursor()
cursor2.execute(sql2)
print "<select name='qui_id' id='qui_id' class='ddquiz'>"
print "<option value=''><i>(Select Quiz)</i></option>"
for row2 in cursor2:
qui_id = row2[0]
qui_quiz = row2[1]
#print "<option value=>" + qui_quiz
print "<option value=" + str(qui_id) + ">" + str(qui_quiz) + "</option>"
print "</select>"
print "</td>"
print "</tr>"
print "<tr>"
print "<td><input type = 'submit' value = 'Submit' /></td>"
print "</tr>"
print "</table>"
print "</form>"
#start here:
init()
print "</body>"
print "</html>"
Add A New Quiz Question And Custom Alert Box (questions-for-quiz-admin.py)

Here’s the code for questions-for-quiz-admin.py:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Enter Questions For Quiz</title>"
#jquery
#print "<script src='https://code.jquery.com/jquery-3.5.0.js'></script>"
#these work with the dynamic alert box
#this makes the dialog look like a dialog box
print "<link rel='stylesheet' type='text/css' href='https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css'>"
#this makes the dialog function correctly
print "<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>"
print "<script type='text/javascript' src='https://code.jquery.com/ui/1.11.4/jquery-ui.min.js'></script>"
'''works
#basic alert box:
print "<script>"
print "$(document).ready(function(){"
print " // Get value on button click and show alert"
print " //$('#action').click(function(){"
print " var str = $('#action').val();"
#print " alert(str);"
print " if(str != 'normal'){"
print " alert(str);"
print " };"
print " //});"
print "});"
print "</script>"
'''
print "<style id='compiled-css' type='text/css'>"
print " .showcss{ display:block; }"
print " .hidecss{ display:none; }"
print " /* EOS */"
print " </style>"
print "<script>"
print "$(document).ready(function() {"
print " //$('#btnTest').click(function() {"
print " ShowCustomDialog();"
print " //});"
print "});"
#modified from http://jsfiddle.net/eraj2587/Pm5Fr/14/
print "function ShowCustomDialog() {"
print " var str = $('#action').val();"
#print " ShowDialogBox('Warning', 'Record updated successfully.', 'Ok', '', 'GoToAssetList', null);"
print " ShowDialogBox(str, 'Updated', 'Ok', '', 'GoToAssetList', null);"
print "}"
print "function ShowDialogBox(title, content, btn1text, btn2text, functionText, parameterList) {"
print " var btn1css;"
print " var btn2css;"
print " if (btn1text == '') {"
print " btn1css = 'hidecss';"
print " } else {"
print " btn1css = 'showcss';"
print " }"
print " if (btn2text == '') {"
print " btn2css = 'hidecss';"
print " } else {"
print " btn2css = 'showcss';"
print " }"
#print " $('#lblMessage').html(content);"
print " $('#dialog').dialog({"
print " resizable: false,"
print " title: title,"
print " modal: true,"
print " width: '400px',"
print " height: 'auto',"
print " bgiframe: false,"
print " hide: {"
print " effect: 'scale',"
print " duration: 400"
print " },"
print " buttons: [{"
print " text: btn1text,"
print " 'class': btn1css,"
print " click: function() {"
print " $('#dialog').dialog('close');"
print " }"
print " },"
print " {"
print " text: btn2text,"
print " 'class': btn2css,"
print " click: function() {"
print " $('#dialog').dialog('close');"
print " }"
print " }"
print " ]"
print " });"
print "}"
print "</script>"
print "</head>"
print "<body>"
#GLOBAL VARIABLES
USERNAME = 'admin'
PASSWORD = 'db-admin'
DB = 'online-quiz'
import MySQLdb
import os
#import requests #this script doesn't like this (doesn't fail, just blank screen)
# Import modules for CGI handling
import cgi, cgitb
def init():
#read the query params
params = os.environ.get('QUERY_STRING')
#DEBUG:
#print 'params= ' + str(params)
#print '<br>'
#print '<br>'
res = params.split('=') #TESTS THAT THERE IS A QUERY STRING
#display based on if params were sent
if str(res) == "['']":
#DEBUG:
print ('<font size=6 color=red>You should not be here</font>')
print '<br><br>'
print "<font size=4 color=red><a href='index.py'>You need to login first.</a></font>"
else:
#DEBUG:
#print ('some params were passed - show them')
#get the field values
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('question'):
question = form.getvalue('question')
else:
question = "Not set"
#this is the main question id
if form.getvalue('quid'):
quid = form.getvalue('quid')
else:
quid = "Not set"
if form.getvalue('qans'):
qans = form.getvalue('qans')
else:
qans = "Not set"
#----------------------------
searchParams = [i.split('=') for i in params.split('&')] #parse query string
for key, value in searchParams:
#DEBUG:
#print('<b>' + key + '</b>: ' + value + '<br>\n')
#show the quizzes for user and allow for data entry
if key == 'id':
#when the form initializes, it should be blank
quiz = "Not set"
quid = value
#-------------------------
#show the quiz name
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql = "SELECT qui_quiz FROM tblQuizzes WHERE qui_id=" + value
cursor.execute(sql)
conn.commit()
rec1= cursor.fetchone()
#print ("<h2>'"+ str(rec1[0]) + "'</h2>")
#todo: we need to know what the name of the quiz is!
print("<h4>Enter And List Questions For This Quiz</h4>")
#for row in cursor:
# qui_quiz = row[0]
# Close the connection
conn.close()
#-------------------------
show_form(quid,'Add Question')
#********************
#insert the contents of the form into the table
#********************
#DEBUG:
#print ("INIT quid="+ str(value) + "<br>")
show_table(value)
elif key == 'insert':
#print("<h2>Insert Record</h2>")
insert_values(quid,question,qans)
show_form(quid,'Question Added')
show_table(quid)
elif key == 'edit':
#print("<h2>Edit Record</h2>")
#uses cgi to parse the querystring, and ability to access individual arguments
#quid = cgi.parse_qs( params )["quid"][0]
qid = cgi.parse_qs( params )["edit"][0]
mainid = cgi.parse_qs(params)["main"][0]
#-------------------------
#show the clicked record.
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql = "SELECT qud_question,qud_correct_answer FROM tblQuizzesDetail WHERE qud_id=" + qid
cursor.execute(sql)
conn.commit()
for row in cursor:
qui_quiz = row[0]
qui_answer = row[1]
# Close the connection
conn.close()
#-------------------------
#show the edit version of the form
#show_form_edit(quid,qid,qui_quiz)
#print('show form')
show_form_edit(mainid,qid,qui_quiz,qui_answer,'Edit Question')
show_table(mainid)
elif key == 'edit2':
#print('edit2 now')
#userid = form.getvalue('userid')
mainid = cgi.parse_qs(params)["main"][0]
qud_id = form.getvalue('quid')
qud_question = form.getvalue('question')
answer = form.getvalue('qans')
#print ("<br>mainid="+ str(mainid) + "<br>")
#print ("<br>qud_id="+ str(qud_id) + "<br>")
#print ("qud_question="+ str(qud_question) + "<br>")
#update_values(qud_id,qud_qustion,userid)
update_values(qud_id,qud_question,answer)
#print('show form')
#show_form(qud_id,'edit')
show_form(mainid,'Record Updated')
show_table(mainid)
elif key == 'delete':
#print("<h2>Delete Record</h2>")
#print ("<br>params: "+ str(params) + "<br>")
#uses cgi to parse the querystring, and ability to access individual arguments
qid = cgi.parse_qs(params)["delete"][0]
mainid = cgi.parse_qs(params)["main"][0]
#print ("<br>qid: "+ str(qid) + "<br>")
##print ("<br>delete qid="+ str(qid) + "<br>")
delete_values(mainid,qid)
#show_form(quid,'Question Deleted')
show_form(mainid,'Question Deleted')
show_table(mainid)
#----------------------------
def insert_values(quid,question,qans):
#DEBUG
#print ("<br><br>insert_values<br><br>")
#print ("quid="+ str(quid) + "<br>")
#print ("quiz="+ str(question) + "<br>")
#print ("qans="+ str(qans) + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
#Python will handle the escape string for apostrophes and other invalid SQL characters for you
# %d or %i should be used for integer or decimal values.
# %s is used for string values
sql = "INSERT INTO tblQuizzesDetail (qud_main_id,qud_question,qud_correct_answer) VALUES (%s, %s, %s)"
args=(quid, question,qans)
try:
cursor.execute(sql, args)
#add this to make sure you data is being inserted
conn.commit()
#print "<br><font color=green>****************RECORD INSERTED****************</font><br>"
#print ("<h3><a href='quiz-questions-admin.py?id=" + str(quid) + "'>Back</a></h3>")
except error as e:
print("error")
print(e)
return None
# Close the connection
conn.close()
def update_values(quiz_id,quiz,answer):
#DEBUG
#print("update = " + str(quiz) + " with " + str(answer) + " - for QUIZ=" + str(quiz_id) + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
#Python will handle the escape string for apostrophes and other invalid SQL characters for you
sql = "UPDATE tblQuizzesDetail SET qud_question = %s , qud_correct_answer = %s WHERE qud_id =%s"
#print "sql=" + sql
cursor.execute(sql, (quiz,answer,quiz_id))
conn.commit()
#print '<br><font color=green>**************Record Updated**************<br>'
#print ("<h3><a href='enter-quizzes.py?id=" + str(userid) + "'>Back</a></h3>")
# Close the connection
conn.close()
def delete_values(arg,quid):
#DEBUG
#print("delete fx = " + arg + " - for quid=" + quid + "<br>")
conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql="DELETE FROM tblQuizzesDetail WHERE qud_id=" + quid
#print ("sql="+ str(sql) + "<br>")
try:
cursor.execute(sql)
conn.commit()
#print "<br><font color=red>****************RECORD DELETED****************</font><br>"
#print ("<h3><a href='quiz-questions-admin.py?id=" + str(arg) + "'>Back</a></h3>")
except error as e:
print(e)
return None
print "<br><font color=red>****************DELETION FAILED!****************</font><br>"
# Close the connection
conn.close()
def show_table(quid):
#DEBUG:
# print("show table<br>")
conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)
cursor = conn.cursor()
sql2="SELECT * FROM tblQuizzesDetail WHERE qud_main_id = " + quid
#DEBUG:
#print("show table<br>" + str(sql2) + "<br>")
cursor.execute(sql2)
conn.commit()
# Get the number of rows in the result set
numrows = cursor.rowcount
#css
#print "<br><br>**********************<br><br>"
#print "<input type='button' id ='btnTest' value='Test'/>"
print "<div id='dialog' title='Alert message' style='display: none'></div>"
#print "<label id='lblMessage'></label>"
# print "<br><br>**********************<br><br>"
print "<table width='100%' border='1px'>"
print "<th>Edit</th><th>Delete</th><th>Question</th><th>Answer</th>"
# Get and display all the rows
for row in cursor:
qid = row[0]
quiz = row[1]
print '<tr>'
print '<td width=2%>'
print "<a href='quiz-questions-admin.py?edit=" + str(qid) + "&main=" + str(quid) +"'>Edit</a>" #need to convert the index to a string
print '</td>'
print '<td width=2%>'
print "<a href='quiz-questions-admin.py?delete=" + str(qid) + "&main=" + str(quid) +"'>Delete</a>" #need to convert the index to a string
print '</td>'
print '<td>' + str(row[2]) + '</td>'
print '<td>' + str(row[3]) + '</td>'
print '</tr>'
print '</table>';
# Close the connection
conn.close()
def show_form(quid,action1):
#DEBUG:
#print("show form<br>")
print "<form name='frmRegular' action = 'quiz-questions-admin.py?insert=1&main=" + str(quid) +"' method = 'post'>"
print "<table width='500px' border='0px' bgcolor=lightgreen>"
print "<tr>"
print "<td><strong>Main Quiz ID:</strong></td>"
print "<td><input type = 'text' style='background-color:grey' readonly name = 'quid' value='" + str(quid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><!--action--></td>"
print "<td><input type = 'hidden' id = 'action' value='" + str(action1) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Question:</strong></td>"
print "<td><input type = 'text' name = 'question' value=''></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Answer:</strong></td>"
print "<td><select name='qans' id='qans'>"
print " <option value='1'>Yes</option>"
print " <option value='0'>No</option>"
print "</select></td>"
print "</tr>"
print "<tr>"
print "<td><input type = 'submit' value = 'Submit' /></td>"
print "</tr>"
print "</table>"
print "</form>"
def show_form_edit(mainid,qid,qui_quiz,qui_answer,action1):
#DEBUG:
#print("show form<br>")
print "<form name='frmEdit' action = 'quiz-questions-admin.py?edit2=1&main=" + str(mainid) +"' method = 'post'>"
print "<table width='500px' border='0px' bgcolor=lightgreen>"
print "<tr>"
print "<td><!--action--></td>"
print "<td><input type = 'hidden' id = 'action' value='" + str(action1) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Quiz ID:</strong></td>"
print "<td><input type = 'text' readonly style='background-color:grey' name = 'quid' value='" + str(qid) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Quiz:</strong></td>"
print "<td><input type = 'text' name = 'question' value='" + str(qui_quiz) + "'></td>"
print "</tr>"
print "<tr>"
print "<td><strong>Answer:</strong></td>"
print "<td><select name='qans' id='qans' value='" + str(qui_answer) + "'>"
print " <option value='1'>Yes</option>"
print " <option value='0'>No</option>"
print "</select></td>"
print "</tr>"
print "<tr>"
print "<td><input type = 'submit' value = 'Submit Edit' /></td>"
print "</tr>"
print "</table>"
print "</form>"
#start here:
init()
print "</body>"
print "</html>"
>>>Click to see it in action together<<<
Login With: (We created this login form on another post -> Click here)
User Name = ‘demo’
Password = ‘123’
Let me know if you have any questions.