#!/usr/bin/python
#=====================================================================================
# Get data from a MySql database
#===================================================================================== 
import pymysql as mydb                  #Mysql 3x database driver
  
print("Content-Type: text/html \n")    #required http response header (w/ extra line)

print('''
    <html>
    <head>
    <title>From a database to html</title>
    </head>
    <body>
    <h2>Test Python Database Connection to MySQL</h2>
''')
 
host   = 'localhost'               #the local host
port   =  3306                     #MySql port number
userid = 'demo'                    #the userid
pswd   = 'demo'                    #the password    
db     = 'demo'                    #the name of the mysql database
 
sql = 'select * from student'        #build your query

try:
    conn = mydb.connect(host=host,user=userid,password=pswd,database=db)     #connect to host     
    cursor = conn.cursor()                          #create a cursor 
    cursor.execute(sql);                            #execute the query
except mydb.Error as e:
    print("Could not establish connection", '<br>') 
    print(e.errno, e.msg, '<br>')
    exit()

numOfRow = cursor.rowcount                      #number of rows retrieved
numOfCol = len(cursor.description)              #number of columns retrieved 

#---Build a dictionary of column name/value-----------------------------
def build_list_dict(cursor):
    data = []
    metadata = cursor.description               #get column information
    results  = cursor.fetchall()                #get all the rows at once
    for row in results:                         #loop thru all returned rows
        i=0
        dict1 = {}
        for col_value in row:                   #loop thru all columns for each row
            col_info = metadata[i]              #description is info about each column 
            col_name = col_info[0]              #1st element is column name
            dict1[col_name] = col_value         #build dictionary of column name/value
            i+=1
        data.append(dict1)                      #append the dictionary to the data list
    return data
#-------------------------------------------------------------------------------

data = build_list_dict(cursor)                  #call the above function
numOfRow = cursor.rowcount                      #number of rows retrieved
numOfCol = len(cursor.description)              #number of columns retrieved 


#---Print the data------------------------------------------------------
col_names = data[0].keys()                      #get all the column names

print("<table border=1>")
print("<tr bgcolor=tan>", end='')
for col_name in col_names:                      #loop thru the column names
    print("<th>", col_name, end='')             #print the column name
print("</tr>")

for row in data:                                #loop thru the data rows
    print("<tr>", end='')
    for (col_name,col_value) in row.items():    #loop thru name/value pairs
        print("<td>", col_value, end='')        #print the column value
    print("</tr>")

print("<tr bgcolor=tan>", end='')
print("<td colspan=5> Number of Rows: ", numOfRow, end='')  
print("</tr>")
    

#---Print column name headers----------------------------------------
#print("<tr bgcolor=tan>", end='')
#for colInfo in cursor.description :
#    col_name     = colInfo[0]           #the column name
#    col_type     = colInfo[1]           #the column type
#    col_nullable = colInfo[6]           #is column nullable
#    print("<th>", col_name, end='')
#print('</tr>')

#---Option one (get all the rows)----------------------------------------
#results = cursor.fetchall()             #get all the rows at once
#for row in results:                     #loop thru the list of rows
#    print('<tr>', end='')
#    for col in row:                     #loop thru the tuple of columns                     
#        print('<td>', col, end='') 
#    print('</tr>') 

#---Option two  (get one row at a time)----------------------------------
#row = cursor.fetchone()                  #get one row at a time
#while row is not None:                   #loop until no more rows
#    print('<tr>', end='')
#    for col in row :                     #for every column in the row
#        print('<td>', col, end='')
#    print('</tr>') 
#    row = cursor.fetchone()
#------------------------------------------------------------------------

print("</table>")

cursor.close()                          #close the cursor/buffer
conn.close()                            #close the connection



#=== 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
#=================================================================================