Python And MySQL | Python In HTML Examples https://pythoninhtmlexamples.com Showing You How You Can Use Python On Your Website Tue, 27 Oct 2020 21:20:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 194754043 How To Make A Select Drop Down List In Python https://pythoninhtmlexamples.com/how-to-make-a-select-drop-down-list-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-make-a-select-drop-down-list-in-python Tue, 27 Oct 2020 17:43:18 +0000 https://pythoninhtmlexamples.com/?p=258 (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 "Select Quiz Dropdown Example" print "" print "" print "" print "" print "" #GLOBAL VARIABLES USERNAME = 'admin' PASSWORD = 'pwd' DB […]

The post How To Make A Select Drop Down List In Python first appeared on Python In HTML Examples.]]>

(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 "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 "
" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "
User:
Select Quiz From List:" conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB) sql="SELECT qui_id,qui_quiz FROM tblQuizzes WHERE qui_user_id = " + str(userid) #many errors occur because you called a variable that doesn't exist (ex. you call "sql2", but it doesn't exist anywhere) cursor = conn.cursor() cursor.execute(sql) print "" print "
" print "
" #start here: init(1) print "" 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 "&lt;select name='qui_id' id='qui_id' class='ddquiz'&gt;"
	print "&lt;option value=''&gt;&lt;i&gt;(Select Quiz)&lt;/i&gt;&lt;/option&gt;"
	for row in cursor:
		qui_id = row[0]
		qui_quiz = row[1]

		#print "&lt;option value=&gt;" + qui_quiz
		print "&lt;option value=" + str(qui_id) + "&gt;" + str(qui_quiz) + "&lt;/option&gt;"

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 "&lt;option value=" + str(qui_id) + "&gt;" + str(qui_quiz) + "&lt;/option&gt;"

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

FacebooktwitterredditpinterestlinkedinmailThe post How To Make A Select Drop Down List In Python first appeared on Python In HTML Examples.]]>
258
Python Project – Online Quiz Management – Adding Quizzes https://pythoninhtmlexamples.com/python-project-online-quiz-management-adding-quizzes/?utm_source=rss&utm_medium=rss&utm_campaign=python-project-online-quiz-management-adding-quizzes Sat, 17 Oct 2020 20:33:28 +0000 https://pythoninhtmlexamples.com/?p=224 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 […]

The post Python Project – Online Quiz Management – Adding Quizzes first appeared on Python In HTML Examples.]]>
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.

FacebooktwitterredditpinterestlinkedinmailThe post Python Project – Online Quiz Management – Adding Quizzes first appeared on Python In HTML Examples.]]>
224
Python Project – Online Quiz Management – Add Edit Delete https://pythoninhtmlexamples.com/python-project-online-quiz-management-add-edit-delete/?utm_source=rss&utm_medium=rss&utm_campaign=python-project-online-quiz-management-add-edit-delete Thu, 01 Oct 2020 19:43:21 +0000 https://pythoninhtmlexamples.com/?p=233 The following code will allow you to: -Enter (insert) new quizzes -Modify (Update) existing ones -Delete quizzes you don’t want. (Click image to see it in action – login with “demo” and “123”) Click here for the main project link #!/usr/bin/python print "Content-type: text/html\n\n" print "<html>" print "<head>" print "<title>Enter Quizes</title>" print "</head>" print "<body>" […]

The post Python Project – Online Quiz Management – Add Edit Delete first appeared on Python In HTML Examples.]]>
The following code will allow you to:

-Enter (insert) new quizzes
-Modify (Update) existing ones
-Delete quizzes you don’t want.

(Click image to see it in action – login with “demo” and “123”)

Click here for the main project link

#!/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   = 'db_user'
PASSWORD = 'pwd'
DB = 'database-name'

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

Click For A Working Sample

FacebooktwitterredditpinterestlinkedinmailThe post Python Project – Online Quiz Management – Add Edit Delete first appeared on Python In HTML Examples.]]>
233
Python Project – Login Form https://pythoninhtmlexamples.com/python-project-login-form/?utm_source=rss&utm_medium=rss&utm_campaign=python-project-login-form Sat, 26 Sep 2020 20:13:48 +0000 https://pythoninhtmlexamples.com/?p=212 This login form is probably going to be used for many projects, so it’s in a post all by itself. #!/usr/bin/python print "Content-type: text/html\n\n" print "<html>" print "<head>" print "<title>Login To Online Quiz</title>" print "</head>" print "<body>" #GLOBAL VARIABLES USERNAME = 'username' PASSWORD = 'password' DB = 'mysql-database' import MySQLdb import os #import requests #this […]

The post Python Project – Login Form first appeared on Python In HTML Examples.]]>
This login form is probably going to be used for many projects, so it’s in a post all by itself.

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Login To Online Quiz</title>"
print "</head>"
print "<body>"

#GLOBAL VARIABLES
USERNAME   = 'username'
PASSWORD = 'password'
DB = 'mysql-database'

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 ('no query params')
		#print '<br>'

		print "<h2>Login</h2>"
		print "<form action = 'index.py?login=1' method = 'post'>"

		print "<table width='100%' border='0px' bgcolor=lightgreen>"

		print "<tr>"
		print "<td><strong>User Name:</strong></td>"        
		print "<td><input type = 'text' name = 'uname' placeholder='enter username'></td>"
		print "</tr>"

		print "<tr>"
		print "<td><strong>Password:</strong></td>"        
		print "<td><input type = 'text' name = 'pword' placeholder='enter password'></td>"
		print "</tr>"

		print "<tr>"
		print "<td><input type = 'submit' value = 'Login' /></td>"
		print "</tr>"

		print "</table>"

		print "</form>"


	else:
		#DEBUG:
		#print ('some params were passed - show them')
		#print '<br>'
		
		#searchParams is an array of type [['key','value'],['key','value']]	
		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 == 'login':
				form = cgi.FieldStorage() 
				uname = form.getvalue('uname')
				pword = form.getvalue('pword')

				#print ("login: " + uname + " " + pword + "<br>now call login<br><br>")			
				login(uname,pword)
	

def login(username,password):

	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 = "SELECT `u_login`, `u_password` FROM `tblUsers` WHERE u_login = %s AND u_password= %s "

	cursor.execute(sql, (username, password))

	# Get the number of rows in the result set
	numrows = cursor.rowcount
	
	#DEBUG:
	#print('<br><br>numrows = ' + str(numrows) + '<br><br>' ) 	
	
	if numrows > 0:	
		print '<font color=green>**************Login Successful**************</font><br><br>Please wait while we redirect you...'
	else:
		print '<font color=red>**************Login Failed**************</font><br><br>'
		print "<a href='index.py'>Try Again</a>"

	# Close the connection
	conn.close()    

	
#start here:
init()


print "</body>"
print "</html>"

Click here to see it in action

BTW: The user name and password are
demo
123

Click here for the online quiz management main project link

FacebooktwitterredditpinterestlinkedinmailThe post Python Project – Login Form first appeared on Python In HTML Examples.]]>
212
Python Project – Online Quiz Management https://pythoninhtmlexamples.com/python-project-online-quiz-management/?utm_source=rss&utm_medium=rss&utm_campaign=python-project-online-quiz-management Fri, 25 Sep 2020 18:36:30 +0000 https://pythoninhtmlexamples.com/?p=187 I am going to be implementing some Python projects with a browser front end (obviously since that’s what this domain is called), I am going to be focusing on the core functionality, not really the aesthetics. You can always use some stylesheets (CSS) to make it look pretty. I am just concerned with the fact […]

The post Python Project – Online Quiz Management first appeared on Python In HTML Examples.]]>
I am going to be implementing some Python projects with a browser front end (obviously since that’s what this domain is called),

I am going to be focusing on the core functionality, not really the aesthetics. You can always use some stylesheets (CSS) to make it look pretty.
I am just concerned with the fact that it works.

The first one is going to show you how to implement an Online Quiz Management System.

(Click the image to see it in action – login: demo, 123)

It will have 2 views – Admin view and End User view:

Admin view

Log inClick here for the code
Add/Edit/Delete new quiz text (Click for code)
-Add questions and answers for the selected quiz

End User view

Log inClick here for the code
-Select the quiz to take
-View the question
-Answer the question
-Tally the result at the end.

Setup

First off we need to setup a MySQL database to hold all the persistent data for our application.

Login to your control panel (mine is on the hostgator webserver) and add a database called “online-quiz”

now add an admin user…

If you need some more information or help, see this post (from a hostmonster perspective).

Now it will show up in the database administration tool (phpMyAdmin)

Now we can start adding tables.

The first will be the users table (tblUsers).

FacebooktwitterredditpinterestlinkedinmailThe post Python Project – Online Quiz Management first appeared on Python In HTML Examples.]]>
187
Adding An Application Switchboard https://pythoninhtmlexamples.com/adding-an-application-switchboard/?utm_source=rss&utm_medium=rss&utm_campaign=adding-an-application-switchboard Fri, 16 Aug 2019 15:20:05 +0000 http://pythoninhtmlexamples.com/?p=120 We want to direct “traffic” to where we want them to go, so we are going to add a navigational component called a “switchboard”. Any page that’s called index.htm or index.php is going to show up first, when someone enters that URL. That looks more professional than just seeing a list of files in that […]

The post Adding An Application Switchboard first appeared on Python In HTML Examples.]]>
We want to direct “traffic” to where we want them to go, so we are going to add a navigational component called a “switchboard”.

Any page that’s called index.htm or index.php is going to show up first, when someone enters that URL.

That looks more professional than just seeing a list of files in that folder.

A website is just a folder on a computer, and in order that you don’t see all the files in that folder, you are automatically sent to the index page.

So we create a main switchboard index page with a php extension, because I probably want to program it in the near future, otherwise we could have just used a basic htm page.

The new page we are planning to send the user to is the doctors.py page, which is basically just a copy of the providers python script that we created earlier.

Now here is the code for doctors.py

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Doctors</title>"
print "</head>"
print "<body>"

#GLOBAL VARIABLES
USERNAME   = 'username'
PASSWORD = 'password'
DB = 'db_name'

import MySQLdb
import os

# Import modules for CGI handling 
import cgi, cgitb

def init():

   
    #read the query params
    params = os.environ.get('QUERY_STRING')
    
    #RECORD ALREADY EXISTS

    #------------------------------------------------------------------------------------
    #["id"] - just selects the "id" parameter, but the [0] selects the actual value
    arg = cgi.parse_qs( params )["id"][0]

    #["action"] - just selects the "action" parameter, but the [0] selects the actual value
    action = cgi.parse_qs( params )["action"][0]

    #["ltype"] - just selects the "ltype" parameter, but the [0] selects the actual value
    ltype = cgi.parse_qs( params )["ltype"][0]    
    #------------------------------------------------------------------------------------

    #Python has no switch case statement
    if action == 'edit':

        #---------------------------------------------------------------
        #1. show the clicked record.
        conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
        cursor = conn.cursor()           
        sql = "SELECT * FROM tblDoctors WHERE doc_id=" + arg            
        cursor.execute(sql)
        for row in cursor:
            fname = row[1]            
            city = row[2]

        print "****************EDIT RECORD****************"
        # Close the connection
        conn.close()

        edit_form(arg,fname,city)

        #show_table()
           
    if action  == 'update':
        #---------------------------------------------------------------
        #2.Update the new values
        #---------------------------------------------------------------
        
        form = cgi.FieldStorage() 

        # Get data from fields
        if form.getvalue('fname'):
           fname = form.getvalue('fname')
        else:
           fname = "Not set"

        if form.getvalue('city'):
           city = form.getvalue('city')
        else:
           city = "Not set"
           
        update_values(fname,city,arg)              

        edit_form(arg,fname,city)

        #show_table()
        
    if action == 'delete':
        fname = ''            
        city = ''    
        delete_values(arg)   

        edit_form(arg,fname,city)

        #show_table()
        
    if action == 'create':
        if ltype == 'b':
            #print 'create the new record.<br>'
            fname = ''            
            city = ''
                    
            form = cgi.FieldStorage() 

            # Get data from fields
            if form.getvalue('fname'):
               fname = form.getvalue('fname')
            else:
               fname = "Not set"

            if form.getvalue('city'):
               city = form.getvalue('city')
            else:
               city = "Not set"            
            insert_values(fname,city)  

            edit_form(arg,fname,city)
            
        elif ltype == 'l':
            
            add_form()
            
            
        #print ltype + ' showtable<br>'
        #show_table()

    if action == 'list':
        add_form()

        #show_table()
        

    show_table()
    
def edit_form(arg,fname,city):

    #read the values from the database

    print "<h2>Edit Record</h2>"
    print "<form action = 'doctors.py?id=" + arg + "&action=update&ltype=0' method = 'post'>"
    
    print "<table width='100%' border='0px' bgcolor=lightgreen>"

    print "<tr>"
    print "<td><strong>First Name:</strong></td>"        
    print "<td><input type = 'text' name = 'fname' value='" + fname + "'></td>"
    print "</tr>"

    print "<tr>"
    print "<td><strong>City:</strong></td>"        
    print "<td><input type = 'text' name = 'city' value='" + city + "'></td>"
    print "</tr>"

    print "<tr>"
    print "<td><input type = 'submit' value = 'Edit' /></td>"
    print "</tr>"
    
    print "</table>"

    print "</form>"


    #show_table()

def add_form():
        #CREATE THE NEW RECORD ONLY IF THE ACTION IS CREATE
        #default values
        fname=''
        city=''

        print "<h2>New Record 3</h2>"
        print "<form action = 'doctors.py?id=0&action=create&ltype=b' method = 'post'>"
        
        print "<table width='100%' border='0px' bgcolor=lightgreen>"

        print "<tr>"
        print "<td><strong>First Name:</strong></td>"        
        print "<td><input type = 'text' name = 'fname' value='" + fname + "'></td>"
        print "</tr>"

        print "<tr>"
        print "<td><strong>City:</strong></td>"        
        print "<td><input type = 'text' name = 'city' value='" + city + "'></td>"
        print "</tr>"

        print "<tr>"
        print "<td><input type = 'submit' value = 'Submit' /></td>"
        print "</tr>"
        
        print "</table>"

        print "</form>"

        #show_table()
        
def update_values(firstname,cty,arg):

    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 tblDoctors SET doc_name = %s, doc_city = %s WHERE doc_id =%s"
    cursor.execute(sql, (firstname, cty,arg))

    print '**************Record Updated**************'

    #Commit your changes
    conn.commit()
    
    # Close the connection
    conn.close()
    
def delete_values(id):

    conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)

    cursor = conn.cursor()
   
    sql="DELETE FROM tblDoctors WHERE doc_id=" + id
    
    cursor.execute(sql)

    #Commit your changes
    conn.commit()

    print "****************RECORD DELETED****************"
    # Close the connection
    conn.close()
    
def insert_values(firstname,cty):

    conn = MySQLdb.connect('localhost',USERNAME,PASSWORD,DB)
    conn.autocommit(True)
    
    cursor = conn.cursor()
    
    #Python will handle the escape string for apostrophes and other invalid SQL characters for you
    
    sql = "INSERT INTO tblDoctors (doc_name,doc_city) VALUES (%s, %s)"
    cursor.execute(sql, (firstname, cty))

    print '**************Record Added**************'

    #Commit your changes
    conn.commit()
    
    # Close the connection
    conn.close()    
    
def show_table():

    conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)

    curs = conn.cursor()
    
    sql="SELECT SQL_NO_CACHE * FROM tblDoctors ORDER BY doc_id"

    curs.execute(sql)
    #rows = cursor.fetchall();
     
    
    # Get the number of rows in the result set
    rows = curs.fetchall();
    numrows = curs.rowcount    
    print "numrows = " + str(numrows) + '<br>';
    
    
    print "<table width='100%' border='1px'>"
    print "<th width=3%></th><th width=3%></th>"
    print "<th>First Name</th><th>City</th>"
    # Get and display all the rows
    for row in rows:

        id = row[0]
        
        print '<tr>'
        print '<td>'
        print "<a href='doctors.py?id=" + str(id) + "&action=edit&ltype=0'>Edit</a>" #need to convert the index to a string
        print '</td>'
        print '<td>'
        print "<a href='doctors.py?id=" + str(id) + "&action=delete&ltype=0'>Delete</a>" #need to convert the index to a string
        print '</td>'         
        print '<td>' + row[1] + '</td>'
        print '<td>' + row[2] + '</td>'
        print '</tr>'

    print '<tr>'
    print '<td colspan=3>'        
    print "<a href='doctors.py?id=0&action=list&ltype=0'>Add New Record</a>" 
    print '</td>'
    print '</tr>'
    print '</table>';

    cursor.close()
    
    # Close the connection
    conn.close()

#start here:
init()


print "</body>"
print "</html>"

Watch how it’s done:

FacebooktwitterredditpinterestlinkedinmailThe post Adding An Application Switchboard first appeared on Python In HTML Examples.]]>
120
Use The Data Entry Form To Have Python Insert Data Into MySQL https://pythoninhtmlexamples.com/use-the-data-entry-form-to-have-python-insert-data-into-mysql/?utm_source=rss&utm_medium=rss&utm_campaign=use-the-data-entry-form-to-have-python-insert-data-into-mysql Fri, 09 Aug 2019 17:44:01 +0000 http://pythoninhtmlexamples.com/?p=93 In our previous post we showed how to enter data into a data entry form and display the values on the screen. In this post, we will continue the concept, but we are actually going to enter it into our MySQL database. Here are a few changes we are making: Python Global Variables In A […]

The post Use The Data Entry Form To Have Python Insert Data Into MySQL first appeared on Python In HTML Examples.]]>
In our previous post we showed how to enter data into a data entry form and display the values on the screen.

In this post, we will continue the concept, but we are actually going to enter it into our MySQL database.

Here are a few changes we are making:

Python Global Variables In A Module

We are going to use some modular level variables to make our code easier to maintain. Here is a shot:

Python Procedure

We are going to use a Python procedure to handle the inserting of data into our MySQL database.

Here is all the code:

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Providers</title>"
print "</head>"
print "<body>"

#GLOBAL VARIABLES
USERNAME   = 'username'
PASSWORD = 'password'
DB = 'database'

import MySQLdb
import os

# Import modules for CGI handling 
import cgi, cgitb

def init():
    #read the query params
    params = os.environ.get('QUERY_STRING')
    findthis="="

    #find if there is an equal sign in the query param
    #use int to convert the variable to a number from a text value
    intEquals = int(params.find(findthis))

    #test for queryparam or first time you have arrived
    if intEquals > -1:
        #RECORD ALREADY EXISTS
        
        #slice notation like substr
        arg= params[3:]
        print 'show clicked record on form'
        print '<br>'
        print '<br>'
        sql = "SELECT * FROM tblProviders WHERE prv_id=" + arg
        print sql
        print '<br>'
        print '<br>'
        show_table()
        
    else:
        #CREATE THE NEW RECORD
        
        #get the field values
        
        form = cgi.FieldStorage() 

        # Get data from fields
        if form.getvalue('fname'):
           fname = form.getvalue('fname')
        else:
           fname = "Not set"

        if form.getvalue('city'):
           city = form.getvalue('city')
        else:
           city = "Not set"

        #insert the contents of the form into the table

        print "<h2>Enter New Provider:</h2>"
        insert_values(fname,city)  
        
        
        print "<form action = 'providers_add_form_mysql.py' method = 'post'>"
        
        print "<table width='100%' border='0px' bgcolor=lightgreen>"

        print "<tr>"
        print "<td><strong>First Name:</strong></td>"        
        print "<td><input type = 'text' name = 'fname' value='" + fname + "'></td>"
        print "</tr>"

        print "<tr>"
        print "<td><strong>City:</strong></td>"        
        print "<td><input type = 'text' name = 'city' value='" + city + "'></td>"
        print "</tr>"

        print "<tr>"
        print "<td><input type = 'submit' value = 'Submit' /></td>"
        print "</tr>"
        
        print "</table>"

        print "</form>"

        
        show_table()

def insert_values(firstname,cty):

    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 = "INSERT INTO tblProviders (prv_FirstName,prv_City) VALUES (%s, %s)"
    cursor.execute(sql, (firstname, cty))
    
    # Close the connection
    conn.close()
    
def show_table():
    
    conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)

    cursor = conn.cursor()

    sql="SELECT * FROM tblProviders"

    cursor.execute(sql)

    # Get the number of rows in the result set
    numrows = cursor.rowcount

    print "<table width='100%' border='1px'>"
    print "<th>ID</th><th>First Name</th><th>City</th>"
    # Get and display all the rows
    for row in cursor:

        id = row[0]
        
        print '<tr>'
        print '<td>'
        print "<a href='providers_add_form_mysql.py?id=" + str(id) + "'>" + str(id) + "</a>" #need to convert the index to a string
        print '</td>'
        print '<td>' + row[1] + '</td>'
        print '<td>' + row[2] + '</td>'
        print '</tr>'
    
    print '</table>';

    # Close the connection
    conn.close()
    
#start here:
init()


print "</body>"
print "</html>"

Here it is in action:

http://pythoninhtmlexamples.com/files/med/providers_add_form_mysql.py

FacebooktwitterredditpinterestlinkedinmailThe post Use The Data Entry Form To Have Python Insert Data Into MySQL first appeared on Python In HTML Examples.]]>
93
How To Simply Connect Python To MySQL On Your Site https://pythoninhtmlexamples.com/how-to-simply-connect-python-to-mysql-on-your-site/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-simply-connect-python-to-mysql-on-your-site Mon, 05 Aug 2019 21:44:07 +0000 http://pythoninhtmlexamples.com/?p=66 Nearly all the visitors to this website are interested in how to integrate the python programming language into their website. We are going through a website I originally build in PHP and MySQL, and reconstruct the site using python and MySQL. Interesting. This will give some good insight into python concepts. In this post, I […]

The post How To Simply Connect Python To MySQL On Your Site first appeared on Python In HTML Examples.]]>
Nearly all the visitors to this website are interested in how to
integrate the python programming language into their website.

We are going through a website I originally build in PHP and MySQL, and reconstruct the site using python and MySQL.

Interesting. This will give some good insight into python concepts.

In this post, I am going to show you how to simply connect your Python webpage to the MySQL server on your website.

In this small bit of code I am demonstrating a how you can connect your python webpage to your MySQL server.

#!/usr/bin/python

import MySQLdb

def dbconnect(): 
    conn = MySQLdb.connect('localhost', 'username','password', 'database')

    cursor = conn.cursor()

    sql="SELECT * FROM tblContestants"

    cursor.execute(sql)

    #any print items need to be below this line:                             
    print "Content-type: text/html\n\n";
    
    for row in cursor:
        #this prints out the 1st column
        print(row[0]) 

#start here:
dbconnect()

With Python, you can import “modules”. In this case to connect to the MySQL server I’m importing the “MySQLdb” module. I can choose to use the code in this module without trying to recode all of the MySQL logic, which will probably take me months! Trust me, this is easier :).

Note: All procedures in Python begin with the “def” keyword.

Now that new “dbconnect” procedure can be used each time I need to make a connection to the database.

…and there are curly brackets around your procedures, just make sure you make the proper indenting, or else your code WILL FAIL.

Indenting is very important in Python. To make sure your indenting is correct start out with the “IDLE” text editing program that should have come with your installation of Python. I have also used “Dr. Python” in the past.

def dbconnect(): 

My “cursor” is like my recordset, and I can loop through my recordset like this:

    
        print "

These are contestants from a MySQL table:

" for row in cursor: #this prints out the 1st column print(row[0])

Remember that since we are outputting text to the screen, this needs to be present:

print "Content-type: text/html\n\n";

PS. If running your file gives you a 500 error, make sure you set the file permissions to 755.

Here it is in action:

http://pythoninhtmlexamples.com/files/mysql.py

FacebooktwitterredditpinterestlinkedinmailThe post How To Simply Connect Python To MySQL On Your Site first appeared on Python In HTML Examples.]]>
66