Python In HTML Examples https://pythoninhtmlexamples.com Showing You How You Can Use Python On Your Website Tue, 27 Oct 2020 21:44:16 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 194754043 How To Use JQuery In Python Without Importing New Modules https://pythoninhtmlexamples.com/how-to-use-jquery-in-python-without-importing-new-modules/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-jquery-in-python-without-importing-new-modules Tue, 27 Oct 2020 21:23:06 +0000 https://pythoninhtmlexamples.com/?p=256 In this post I am going to show you how you can add jquery to a Python script without adding any new modules. You just need this: #jquery print "<script src='https://code.jquery.com/jquery-3.5.0.js'></script>" #basic alert box: print "<script>" print "$(document).ready(function(){" print " // Get value on button click and show alert" print " $('#submit').click(function(){" print " alert('hello');" […]

The post How To Use JQuery In Python Without Importing New Modules first appeared on Python In HTML Examples.]]>

In this post I am going to show you how you can add jquery to a Python script without adding any new modules.

You just need this:

#jquery
print "<script src='https://code.jquery.com/jquery-3.5.0.js'></script>"

#basic alert box:
print "<script>"
print "$(document).ready(function(){"
print "    // Get value on button click and show alert"
print "    $('#submit').click(function(){"
print "        alert('hello');"
print "    });"
print "});"
print "</script>"

Click to see it in action

The first part is just a call to the jquery library which is online, and the script is sort of like javascript, but it’s more recent.

Any html document script, like jquery needs to be put in the “header” tags within the “script” tag.

The pseudo code can be interpreted as “after the document is loaded on the user’s screen, and the element with the ‘id’ of ‘submit’ is clicked, then show the alert box”.

Here’s all the code in action:

#!/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>"

#basic alert box:
print "<script>"
print "$(document).ready(function(){"
print "    // Get value on button click and show alert"
print "    $('#submit').click(function(){"
print "        var str = $('#action').val();"
print "        alert('hello');"
print "    });"
print "});"
print "</script>"

print "</head>"
print "<body>"

#GLOBAL VARIABLES
USERNAME   = 'admin'
PASSWORD = 'pwd'
DB = 'online-quiz'

import MySQLdb

def init(userid):
	#DEBUG:	
	#print("show form" + str(userid) + "<br>")

	print "<form action = 'jquery.py' 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>"
	
	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)

	#Add A 'Select Quiz' (Blank Row) At The Top Of The Dropdown Box 
	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=" + str(qui_id) + ">" + str(qui_quiz) + "</option>"

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

	print "</table>"

	print "</form>"
	
#start here:
init(1)


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

Click to see it in action

FacebooktwitterredditpinterestlinkedinmailThe post How To Use JQuery In Python Without Importing New Modules first appeared on Python In HTML Examples.]]>
256
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
How To Get Query Parameters In Python https://pythoninhtmlexamples.com/how-to-get-query-parameters-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-get-query-parameters-in-python Sat, 26 Sep 2020 17:21:58 +0000 https://pythoninhtmlexamples.com/?p=201 A necessity is using Python in HTML is the ability to pass query parameters from page to page. You are going to want to do this passing as you move from page to page, or you submit values from the page you are currently on to itself to be entered into the database. This process […]

The post How To Get Query Parameters In Python first appeared on Python In HTML Examples.]]>
A necessity is using Python in HTML is the ability to pass query parameters from page to page.

You are going to want to do this passing as you move from page to page, or you submit values from the page you are currently on to itself to be entered into the database.

This process of passing variables in the url is using the GET action of your form. It supposedly “insecure” versus POST, because it shows the passed values in the url, but check out all the pages you visit that are passing data in the url…

This can be done in various ways (I showed another way on this blog, but this way is cleaner, IMHO), but a functional way I have found to do this is found by clicking the link below:

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

import os


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

	print ("Click this url that has params in address: <a href='https://pythoninhtmlexamples.com/files/python-query-params/index.py?id=5&fname=kelly&lastname=schnerde'>https://pythoninhtmlexamples.com/files/python-query-params/index.py?id=5&fname=kelly&lastname=schnerde</a><br><br>")

	print ("Click this url that has <b>NO</b> params in address: <a href='https://pythoninhtmlexamples.com/files/python-query-params/index.py'>https://pythoninhtmlexamples.com/files/python-query-params/index.py</a><br><br>")


	print ("<br><br><br>********************************************************<br><br><br>")

	res = params.split('=') #TESTS THAT THERE IS A QUERY STRING

	#display based on if params were sent
	if  str(res) == "['']":
		print ('no query params')
		print '<br>'
	else:
		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')			
		

    
#start here:
init()


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

Here is the working sample (remember to CHMOD 755 your file):

https://pythoninhtmlexamples.com/files/python-query-params/index.py

FacebooktwitterredditpinterestlinkedinmailThe post How To Get Query Parameters In Python first appeared on Python In HTML Examples.]]>
201
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
A Brief History Of HTML https://pythoninhtmlexamples.com/a-brief-history-of-html/?utm_source=rss&utm_medium=rss&utm_campaign=a-brief-history-of-html Fri, 17 Apr 2020 20:15:39 +0000 https://pythoninhtmlexamples.com/?p=164 What Is The Concept Of HTML HTML is an acronym for “HyperText Markup Language” and put 2 key concepts together, hypertext and markup language. The language of HTML is used to create documents that use “tags” to determine structure and format. Hypertext provides a way to organize and present data in a way, it’s the […]

The post A Brief History Of HTML first appeared on Python In HTML Examples.]]>
What Is The Concept Of HTML

HTML is an acronym for “HyperText Markup Language” and put 2 key concepts together, hypertext and markup language.

The language of HTML is used to create documents that use “tags” to determine structure and format.

Hypertext provides a way to organize and present data in a way, it’s the first HTML element. It’s purpose is to link documents in a non-linear manner.

Hypertext documents contain active links, aka “pointers, to other informational sources, like other web pages.

The individual using the page and click a link and move to another hypertext area in the same document, or move to another web page altogether.

Microsoft Word uses bookmarks in the document for navigational purposes, also you see that the main idea of the search engine is to provide an index of webpages that link to each other.

One of the reasons for the “World Wide Web’s” incredible growth is because of its intuitive nature. It’s easy to “surf the net” by clicking links on hypertext documents which tie them together.

Hypertext systems are naturally used for navigating and exploring presented information.

The textual term for the linked text is “Hypertext”, and when it pertains to media, like videos, audio, images or other multimedia, we can consider them “Hypermedia”.

Who Came Up With The Idea?

A guy by the name of Ted Nelson came up with the idea for hypertext in 1965. He coined the terms hypertext and hypermedia in 1963 and published them in 1965.

The 1st widely commercialized hypertext product was the HyperCard

The Hypercard was conceived by a fellow named Bill Atkinson, and it was introduced in 1987 by Apple Computer. The application incorporated many hypertext and hypermedia concepts, but was really proprietary and only worked on Mac computers.

According to Wikipedia (https://en.wikipedia.org/wiki/HyperCard):

“HyperCard is a software application and development kit for Apple Macintosh and Apple IIGS computers. It is among the first successful hypermedia systems predating the World Wide Web. HyperCard combines a flat-file database with a graphical, flexible, user-modifiable interface.

HyperCard is based on the concept of a “stack” of virtual “cards”.[5] Cards hold data, just as they would in a Rolodex card-filing device. Each card contains a set of interactive objects, including text fields, check boxes, buttons, and similar common graphical user interface (GUI) elements. Users browse the stack by navigating from card to card, using built-in navigation features, a powerful search mechanism, or through user-created scripts.[6]”

Cross Platform Equivalent

HyperCard was only usable on Apple machines, but “HTML” was and is a cross platform language, which can be used by Microsoft, Apple, Linux, Chromebooks, and all other machines I may have missed.

Also, remember that HTML and the rest of the Web is a client/server system, and Hypercard only works on the Apple Macintosh computer.

FacebooktwitterredditpinterestlinkedinmailThe post A Brief History Of HTML first appeared on Python In HTML Examples.]]>
164
What Is HTML? https://pythoninhtmlexamples.com/what-is-html/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-html Tue, 14 Apr 2020 21:36:36 +0000 http://pythoninhtmlexamples.com/?p=133 HTML – stands for “Hyper Text Markup Language” It’s the basic stuff web pages were written in years ago. Because the web pages were mostly static, this was a way to break up the monotony. You could and some color to your text and change the font size where you wanted. You could even link […]

The post What Is HTML? first appeared on Python In HTML Examples.]]>
HTML – stands for “Hyper Text Markup Language”

It’s the basic stuff web pages were written in years ago. Because the web pages were mostly static, this was a way to break up the monotony. You could and some color to your text and change the font size where you wanted. You could even link to other pages, either related or not related. Pretty cool (for then), now there is something called CSS (Cascading Style Sheets) to store all your web page formatting in one place.

This article will deal with the basics of HTML, and you can use the concepts to apply to CSS.

So when Google came around and had the idea to download the web, basically you could download the web page location (URL), and whatever it linked to, and eventually you would have an listing of all the web pages that linked to each other.

Of course, over time, that algorithm evolved because of ideas, like “what if we categorize the page by what the page is about?”, or “we can base the importance of a site by how many other pages link to it.” etc…

Here are some frequently asked question and answers according to Erik:

What is HTML in simple terms?

HTML is a way of displaying text in a web browser.

You can use HTML to “markup the text” with special tags to format the text the reader is reading.

As I wrote earlier, you can change the color of your text on the screen, or the size of certain letters, or even tell the web browser to show the font as bold, italic, or underlined.

What is HTML used for?

HTML is used to “markup” the plain text on a website and make it nicer to read. It gives you the ability to emphasize certain pieces of text on the screen by giving the text some color, changing the character (font) size, or making some other design changes.

What is HTML and how it works?

HTML uses “tags” which the browser understands to perform a certain action on the text the tags surround. Look for some example tags further down on this post.

What is HTML syntax?:

These are the main tags that you’ll use in your HTML documents. All your html files will have the same structure (4 tags and closing tags):

1. html
2. head
3. title
4. body

Here is an example of HTML syntax:

Notice that is follows a general structure or template, and you can just fill in the template.

<html>
  <head>
    <title></title>
  </head>
  <body>
    <!--this is a comment -->
  </body>
</html>

Here is one example of how HTML syntax can be used.

<font size='24 pts'>This font is 24 pts</font>

This font is 24 pts

*********************************************************************

Here are some other tags:

this is a ordered (numbered) list

  1. Subaru
  2. Honda
  3. Toyota
  4. BMW

this is a unordered (bulleted) list

  • Subaru
  • Honda
  • Toyota
  • BMW

these are paragraphs (1 blank line between each paragraph)

Paragraph 1

Paragraph 2

Paragraph 3

these are line breaks (normally it’s like pressing the “Enter” key on your keyboard) (but since this is WordPress, you will see the same effect as the “p” tag)
Line 1

Line 2

Line 3

<html>
  <head>
    <title>The Title Of This Page Is</title>
  </head>
  <body>
    <!--this is a (comment) ordered (numbered) list -->
    <ol>
      <li>Subaru</li>
      <li>Honda</li>
      <li>Toyota</li>
      <li>BMW</li>
    </ol>
    
    <!--this is a (comment) unordered (bulleted) list -->
    <ul>
      <li>Subaru</li>
      <li>Honda</li>
      <li>Toyota</li>
      <li>BMW</li>
    </ul>

    <p>
    Paragraph 1
    </p>
    
    <p>
    Paragraph 2
    </p>

    <p>
    Paragraph 3
    </p>
    
    Line 1
    <br>
    Line 2
    <br>
    Line 3
        
        
  </body>
</html>

*********************************************************************
HTML is:

-A platform independent language (main platforms (that I know exist), windows, mac, linux, android, iphone, chromebook).
-HTML is not case sensitive language (upper and lower case, it’s all good :)).
-HTML allows you to define the page title, Ordered and unordered lists, defining paragraphs and line breaks, etc.
-HTML can controls fonts, colors, and positioning
-Using HTML we can build tables.

How do browsers work?

Browser’s work by rendering HTML marked up text files. The browser understands that files with a .htm or .hhml extension are web files that can be rendered by the web browser in rich text.

Is HTML coding?

HTML is not scripting or coding. It just marks up text.

We can use something like Javascript to code what the user’s desktop experience will be, and we can use Python or PHP to code for the server and make database connections, and activities.


We will be offering other examples in future articles.

FacebooktwitterredditpinterestlinkedinmailThe post What Is HTML? first appeared on Python In HTML Examples.]]>
133
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