Python In HTML | Python In HTML Examples https://pythoninhtmlexamples.com Showing You How You Can Use Python On Your Website Wed, 11 Jan 2023 21:52:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 194754043 How To Read A CSV Into A HTML Table With Python https://pythoninhtmlexamples.com/how-to-read-a-csv-into-a-html-table-with-python/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-read-a-csv-into-a-html-table-with-python Wed, 11 Jan 2023 21:16:02 +0000 https://pythoninhtmlexamples.com/?p=350 A lot can been done with a CSV (“comma separated value”) file. If you can run a web scraping script on your local machine, you can FTP the results to a FTP site in the ubiquitous CSV format, and then render it on your web page with HTML. The rest of this post demonstrates a […]

The post How To Read A CSV Into A HTML Table With Python first appeared on Python In HTML Examples.]]>
A lot can been done with a CSV (“comma separated value”) file.

If you can run a web scraping script on your local machine, you can FTP the results to a FTP site in the ubiquitous CSV format, and then render it on your web page with HTML.

The rest of this post demonstrates a basic example of how you can read a CSV file into an HTML table using Python.

Add an iframe to your page and point it to your python (py) file:

Here is the code for the file:


#!/usr/bin/python
#import csv  #the module is already present so no need to add it again


#MAKE SURE THE FILE PERMISSIONS ARE 755!!!!

filename = open('file_to_ftp.csv') 


# print HTTP header
print "Content-type: text/html\n\n"

# define an HTML template
print "<!DOCTYPE html>"
print "<html>"
print "<head>"
print "<title>CSVParse</title>"
print "</head>"
print "<body>"

print("<table style='width:100%'>")

print("<tr>")
print("<th>Index</th>")
print("<th>Company</th>")
print("<th>Link</th>")
print("<th>Header</th>")

print("</tr>")

for line in filename:	
    row = line.split(",")
    print("<tr>")
    print ("<td>" + str(row[0]) + "</td>")
    print ("<td>" + str(row[1]) + "</td>")
    print ("<td>" + str(row[2]) + "</td>")
    print ("<td>" + str(row[3]) + "</td>")
    print ("</tr>")


print("</table>")


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


Click here for the file in action.

Let me know if you need assistance.

FacebooktwitterredditpinterestlinkedinmailThe post How To Read A CSV Into A HTML Table With Python first appeared on Python In HTML Examples.]]>
350
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
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
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
How To Use Python To Update MySQL https://pythoninhtmlexamples.com/how-to-use-python-to-update-mysql/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-python-to-update-mysql Tue, 13 Aug 2019 17:49:20 +0000 http://pythoninhtmlexamples.com/?p=115 In this post we will be updating our MySQL database using Python. #!/usr/bin/python print "Content-type: text/html\n\n" print "<html>" print "<head>" print "<title>Update Provider</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 […]

The post How To Use Python To Update MySQL first appeared on Python In HTML Examples.]]>
In this post we will be updating our MySQL database using Python.

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Update Provider</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

        #------------------------------------------------------------------------------------
        #["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]

        #------------------------------------------------------------------------------------
        
        #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 tblProviders WHERE prv_id=" + arg            
            cursor.execute(sql)
            for row in cursor:
                fname = row[1]            
                city = row[2]

                #print fname
                #print city

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

               
        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)              
               
            
        if action == 'delete':
            fname = ''            
            city = ''    
            delete_values(arg)
            
        if action == 'create':
            #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)  


        print "<h2>Edit Record</h2>"
        print "<form action = 'providers_update_form_mysql.py?id=" + arg + "&action=update' 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()

        
        
    else:
        #CREATE THE NEW RECORD ONLY IF THE ACTION IS CREATE
        #default values
        fname=''
        city=''

        print "<h2>New Record</h2>"
        print "<form action = 'providers_update_form_mysql.py?id=0&action=create' 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 tblProviders SET prv_FirstName = %s, prv_City= %s WHERE prv_id =%s"
    cursor.execute(sql, (firstname, cty,arg))

    print '**************Record Updated**************'
    
    # Close the connection
    conn.close()
    
def delete_values(id):

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

    cursor = conn.cursor()
   
    sql="DELETE FROM tblProviders WHERE prv_id=" + id
    
    cursor.execute(sql)

    print "****************RECORD DELETED****************"
    # Close the connection
    conn.close()
    
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))

    print '**************Record Added**************'
    
    # Close the connection
    conn.close()
    
def show_table():
    print '<br><br>'
    print "<a href='http://pythoninhtmlexamples.com/files/med/providers_update_form_mysql.py'>Add New Record</a>"
    print '<br><br>'
    conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)

    cursor = conn.cursor()

    sql="SELECT * FROM tblProviders ORDER BY prv_ID"

    cursor.execute(sql)

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

    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 cursor:

        id = row[0]
        
        print '<tr>'
        print '<td>'
        print "<a href='providers_update_form_mysql.py?id=" + str(id) + "&action=edit'>Edit</a>" #need to convert the index to a string
        print '</td>'
        print '<td>'
        print "<a href='providers_update_form_mysql.py?id=" + str(id) + "&action=delete'>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 '</table>';

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


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

Here it is in action:

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

FacebooktwitterredditpinterestlinkedinmailThe post How To Use Python To Update MySQL first appeared on Python In HTML Examples.]]>
115
How To Have Python Delete From A MySQL Table https://pythoninhtmlexamples.com/how-to-have-python-delete-from-a-mysql-table/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-have-python-delete-from-a-mysql-table Sat, 10 Aug 2019 22:23:25 +0000 http://pythoninhtmlexamples.com/?p=102 In out last post we covered how to add a new record to the MySQL database. In this post will add to the previous and show you how to delete a record from the database. First of all we are going to add 2 new columns to our datasheet below: This will allow us to […]

The post How To Have Python Delete From A MySQL Table first appeared on Python In HTML Examples.]]>
In out last post we covered how to add a new record to the MySQL database. In this post will add to the previous and show you how to delete a record from the database.

First of all we are going to add 2 new columns to our datasheet below:

This will allow us to delete the row we’ve selected:

“http://pythoninhtmlexamples.com/files/med/providers_delete_form_mysql.py?id=14&action=delete”

Notice the “action=delete” parameter.

So basically we will click the link and pass the “action=delete” parameter back to the page. Then we’ll use that value to determine what action we will take.

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

        if action == 'delete':            
            delete_values(arg)
            
        if action == 'create':

If the action is delete then we call the delete_values procedure, passing the record id to the procedure.

def delete_values(id):

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

    cursor = conn.cursor()
   
    sql="DELETE FROM tblProviders WHERE prv_id=" + id
    
    cursor.execute(sql)

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

Here is all the code so far:

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Delete Provider</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

        #------------------------------------------------------------------------------------
        #["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]

        #------------------------------------------------------------------------------------


        #Python has no switch case statement
        if action == 'edit':
            sql = "SELECT * FROM tblProviders WHERE prv_id=" + arg
            print sql
            print '<br>'
            print '<br>'

        if action == 'delete':
            #sql="DELETE FROM tblProviders WHERE prv_id=" + arg
            delete_values(arg)
            
        if action == 'create':
            #print 'create the new record.<br>'
            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)  

        #read the values from the database
        fname=''
        city=''
       
        print "<form action = 'providers_delete_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 = 'Edit' /></td>"
        print "</tr>"
        
        print "</table>"

        print "</form>"


        show_table()

        
        
    else:
        #CREATE THE NEW RECORD ONLY IF THE ACTION IS CREATE

        print "New Record...."

        #default values
        fname=''
        city=''
        
        print "<form action = 'providers_delete_form_mysql.py?id=0&action=create' 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 delete_values(id):

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

    cursor = conn.cursor()
   
    sql="DELETE FROM tblProviders WHERE prv_id=" + id
    
    cursor.execute(sql)

    print "****************RECORD DELETED****************"
    # Close the connection
    conn.close()
    
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))

    print '**************Record Added**************'
    
    # Close the connection
    conn.close()
    
def show_table():
    print '<br><br>'
    print "<a href='http://pythoninhtmlexamples.com/files/med/providers_delete_form_mysql.py'>Add New Record</a>"
    print '<br><br>'
    conn = MySQLdb.connect('localhost', USERNAME,PASSWORD,DB)

    cursor = conn.cursor()

    sql="SELECT * FROM tblProviders ORDER BY prv_ID"

    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>"
    print "<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_delete_form_mysql.py?id=" + str(id) + "&action=edit'>" + str(id) + "</a>" #need to convert the index to a string
        print '</td>'
        print '<td>'
        print "<a href='providers_delete_form_mysql.py?id=" + str(id) + "&action=delete'>" + 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 is in action:
http://pythoninhtmlexamples.com/files/med/providers_delete_form_mysql.py

FacebooktwitterredditpinterestlinkedinmailThe post How To Have Python Delete From A MySQL Table first appeared on Python In HTML Examples.]]>
102
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