#!/usr/bin/python
#=====================================================================================
# Get any data from a mysql database
# Display to an html form
#=====================================================================================
import pymysql as mydb                      #Mysql 3x database driver
  
data      = []                              #2 dim array to hold data
col_names = []                              #1 dim array to hold column names
error_msg = ''                              #message to hold DB error if any

sql  = "SELECT * "                                             #change SQL as you wish 
sql += "FROM student JOIN student_email USING(student_id) " 
sql += "ORDER BY lname, fname"                              

print("Content-Type: text/html \n")         #required http response header (w/ extra line)

#===================================================================================
# Read_data: read any data from a database
#===================================================================================
def read_data(sql):

    global error_msg                                            
      
    try:    
        conn = mydb.connect(host='localhost',db='demo',user='demo',password='demo',port=3306)  #connect to db
     
        cursor = conn.cursor()                                  #create a cursor
          
        result = cursor.execute(sql);                           #execute the query
     
    except mydb.Error as e:
        errorNum  = e.args[0]
        errorMsg  = e.args[1]
        error_msg = 'Database Error - ' + str(errorNum) +' '+ errorMsg
        return      

    row = cursor.fetchone()                 #get first row 
    while row is not None:                  #loop until no more rows
        data.append(row)                    #save in the data[] list
        row = cursor.fetchone()             #get next row

    for metadata in cursor.description:     #loop thru the metadata array
        col_names.append(metadata[0])       #metadata[0] is the column name          
         
    cursor.close()                          #close the cursor/buffer
    conn.close()                            #close the connection

#===================================================================================
# Display: display data on the html page
#===================================================================================
def display():

    print("""
        <html>
        <head>
        <title>Retrieve data from database</title>    
        <style>
            a     {text-decoration:none; color:brown}
            table {font:10pt arial; border:solid 2px black; border-collapse:collapse; margin-left:70px; background-color:#eeeeee; } 
            th,td {border:solid 1px black; padding-left:5px; padding-right:5px; vertical-align:top;}
        </style>
        <body bgcolor=lightyellow>
        <h1><center>Data Retrieved from Database</center></h1>
        <table bgcolor=lightyellow border=1>
        <tr bgcolor=tan>
    """)                           
        
    if error_msg:                                       #if there is an error
        print('<b>', error_msg, '</b>')                 #print it

    for col_name in col_names:                          #loop thru the column headers
        print("<th>" ,col_name, end='')                 #print
    print("</tr>")

    for row in data:                                    #loop thru the data rows
        print ("<tr>", end='')                          #start a table row
        for col in row:                                 #loop thru each column
            print("<td>", col, end='')                  #print
        print ("</tr>")
        
    print("</table>")
    print("</body>")
    print("</html>")

#===================================================================================
# Main code
#===================================================================================
read_data(sql);
display();



#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/staff/sultan/public_html/cgi-bin/python')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================